<?php
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2013 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */

/**
 * ctl_cart
 *
 * @uses b2c_frontpage
 * @package
 * @version $Id: ctl.cart.php 1952 2008-04-25 10:16:07Z flaboy $
 * @copyright 2003-2007 ShopEx
 * @author Wanglei <flaboy@zovatech.com>
 * @license Commercial
 */
class b2c_ctl_wap_cart extends wap_frontpage{

    var $customer_template_type='cart';
    var $noCache = true;
    var $show_gotocart_button = true;

    public function __construct(&$app) {

        parent::__construct($app);
        $this->_response->set_header('Cache-Control', 'no-store, no-cache');
        
        $shopname = app::get('wap')->getConf('wap.name');
        if(isset($shopname)){
            $this->title = app::get('b2c')->_('购物车').''.$shopname;
            $this->keywords = app::get('b2c')->_('订货单_').'_'.$shopname;
            $this->description = app::get('b2c')->_('订货单_').'_'.$shopname;
        }
        $this->set_tmpl('cart');
        $this->mCart = $this->app->model('cart');
        $this->set_no_store();

        //kernel::single('base_session')->start();
        $this->obj_session = kernel::single('base_session');
        $this->obj_session->start();
        $this->member_status = $this->check_login();
        if(!$this->member_status){
            $this->pagedata['login'] = 'nologin';
        }

        $this->objMath = kernel::single("ectools_math");
        $this->pagedata['res_url'] = $this->app->res_url;
        $this->pagedata['request_url'] = $this->gen_url( array('app'=>'b2c','ctl'=>'wap_product','act'=>'get_goods_spec') );
        $this->mCart->unset_data();
    }

    public function index(){

        // echo "789";
        // exit();

        $goodsmdl = app::get('b2c')->model('goods');
        $keywordsModel = $this->app->model('goods_keywords');

        $GLOBALS['runtime']['path'][] = array('link'=>$this->gen_url(array('app'=>'b2c','ctl'=>'wap_cart','act'=>'index')),'title'=>'购物车');
        $this->_common(1);
        $this->_response->set_header('Cache-Control','no-store');
        $current_url = $this->gen_url(array('app'=>'b2c','ctl'=>'wap_cart','act'=>'index'));
        $this->pagedata['go_back_link'] = ($_SERVER['HTTP_REFERER'] != $current_url) ? $_SERVER['HTTP_REFERER'] : 'javascript:window.history.go(-1);';
        setcookie('cart[go_back_link]', $this->pagedata['go_back_link'], 0, kernel::base_url() . '/');
        $this->pagedata['aCart']['subtotal_prefilter'] = $this->objMath->number_minus(array($this->pagedata['aCart']['subtotal'], $this->pagedata['aCart']['discount_amount_prefilter']));

        $goods=$this->pagedata['aCart']['object']['goods'];
        //商品数量
        //获取当前会员id
        $members=array("member_id"=>kernel::single('b2c_user_object')->get_member_session());
        $member_id = $members['member_id'];

        foreach ($goods as $key => $value) {
           $gid[] = $value["params"];
        }

       foreach ($goods as $key => $value) {

            $obj_idents[] = $value['obj_ident'];

            $obj_ident = $value['obj_ident'];
            //首先获取该用户的购物车里的该商品数量
            $sql = "select obj_ident,quantity from sdb_b2c_cart_objects where obj_ident = '$obj_ident' and member_id = '$member_id'";
            $this->db = kernel::database();
            $quantity0[$key] = $this->db->select($sql);
        } 
     //    echo "<pre>";
     // var_dump($quantity0);
        $newquantity = array();
        foreach ($quantity0 as $key => $value) {
            $newquantity[$key] = $value[0];
        }
 //    echo "<pre>";
     // var_dump($newquantity);
        $squantity = 0;
        foreach ($goods as $key => $value) {
            $unit = $goodsmdl->getList('*',array("goods_id"=>$value['obj_items']['products'][0]['goods_id']));
            $keywordsList = $keywordsModel->getList('*',array('goods_id'=>$value['obj_items']['products'][0]['goods_id']));
            $goods[$key]['keyword'] = $keywordsList[0]['keyword'];
            $goods[$key]['unit'] = $unit[0]['unit'];
            $goods[$key]['quantity'] = $newquantity[$key]['quantity'];
            $goods[$key]['good_standard'] = $value['params']['good_standard'];
            //购物车里的所有商品数量
            $squantity += $goods[$key]['quantity'];

        }
        //首先获取该用户的购物车里的所有商品数量！因为库存问题不能查找全部数据
        // $sql = "select quantity,sum(quantity) as squantity from sdb_b2c_cart_objects where member_id = '$member_id'";
        // $this->db = kernel::database();
        // $squantity = $this->db->select($sql);
        $this->pagedata['aCart']['items_quantity'] = $squantity;
        $this->pagedata['aCart']['object']['goods']=$goods;
        //计算商品总价
        $gg = $this->pagedata['aCart'];

        // var_dump($this->pagedata['aCart']);
        // exit;

        foreach ($gg['object']['goods'] as $key => $value) {

            $status = $value['obj_items']["products"][0]["price"]["status"];

            $mlv_price = $value['obj_items']["products"][0]["price"]["mlv_price"];
            $quantity = $value['quantity'];

            $discount_amount_prefilter = $value['discount_amount_prefilter'];
            $price = $value['obj_items']["products"][0]["price"]["price"];

            $member_lv_price = $value['obj_items']["products"][0]["price"]["member_lv_price"];

            // $tot[] = $mlv_price*$quantity;

            //有优惠
            if ($status==1) {
              $sprice[] = $mlv_price*$quantity-($discount_amount_prefilter+($price-$member_lv_price)*$quantity);
            }else{
              //原价
              $sprice[] = $price*$quantity;
            }

            // var_dump($status);
            // var_dump($mlv_price);
            // var_dump($quantity);
            // var_dump($discount_amount_prefilter);
            // var_dump($price);
            // var_dump($member_lv_price);

            // var_dump($sprice);

        }

        // var_dump($sprice);
        // exit();

        $totmoney = '';
        //判断购物车是否只有一个商品，进行计算商品总价
        foreach ($sprice as $key => $value) {
          if (count($sprice)>1) {
             $totmoney +=  $value;
          }else{
             $totmoney = $value;
          }

        }

        // var_dump($totmoney);
        // exit();

        // 购物车页面的商品总价
        $this->pagedata['aCart']['promotion_subtotal'] = $totmoney;

        // var_dump($this->pagedata['aCart']['promotion_subtotal']);
        // exit();

        // $this->pagedata['aCart']['promotion_subtotal'] = $this->objMath->number_minus(array($this->pagedata['aCart']['subtotal'], $this->pagedata['aCart']['subtotal_discount']));
        $this->pagedata['checkout_link'] = $this->gen_url( array('app'=>'b2c','act'=>'checkout','ctl'=>'wap_cart') );

        $cart_json = kernel::single('b2c_cart_json');
        $currency = app::get('ectools')->model('currency');
        $Default_currency = $currency->getDefault();
        $this->pagedata['currency'] = $Default_currency['cur_sign'];
        $fororder_setting = app::get('b2c')->getConf('cart_fororder_setting');//是否开启凑单功能
        $this->pagedata['fororder_show'] = $fororder_setting['fororder']['show'];
        $cur = app::get('ectools')->model('currency');
        $this->pagedata['cart_promotion_display'] = $this->app->getConf('cart.show_order_sales.type');

        //货币格式输出
        $ret = $cur->getFormat();
        $ret =array(
            'decimals'=>$this->app->getConf('system.money.decimals'),
            'dec_point'=>$this->app->getConf('system.money.dec_point'),
            'thousands_sep'=>$this->app->getConf('system.money.thousands_sep'),
            'fonttend_decimal_type'=>$this->app->getConf('system.money.operation.carryset'),
            'fonttend_decimal_remain'=>$this->app->getConf('system.money.decimals'),
            'sign' => $ret['sign']
        );
        $this->pagedata['money_format'] = json_encode($ret);
        $this->pagedata['json'] = $cart_json->get_json($this->pagedata);
        
         $add['isused'] = app::get('b2c')->getConf('system.member.IsUsed');
         $add['pernum'] = app::get('b2c')->getConf('system.product.per.num');
         $this->pagedata['add']=$add;
 //@mo add 2017年5月4日 16:51:48
       //   karson 这段代码导致页面异常卡顿去掉
       // kernel::single('b2c_checkproduct_check')->set_good_cart($this->pagedata['aCart']);
       //add by lkb  购物车发货提示更新
       // $goods=$this->pagedata['aCart']['object']['goods'];

       for ($i=0; $i < count($goods); $i++) { 
           $goods_tips="";
           $goods_tips=$this->ajax_product_goodtips($goods[$i]['obj_items']['products'][0]['product_id'],$goods[$i]['quantity']);
           $this->pagedata['aCart']['object']['goods'][$i]['goods_tips']=$goods_tips;
       }
        ////去掉失效赠品 hzk
  if(count($this->pagedata['aCart']['object']['gift']['order']))
  {
      for($i=0;$i<count($this->pagedata['aCart']['object']['gift']['order']);$i++)
      {
          if($this->pagedata['aCart']['object']['gift']['order'][$i]['quantity']==0)
          {
              unset($this->pagedata['aCart']['object']['gift']['order'][$i]);
          }
      }
  }
//add end 
//add 这里是验证登录状态----未登录不显示商品价格 ---黄智坤06-19
    $userObject = kernel::single('b2c_user_object');
        if( $userObject->is_login()){
            $this->pagedata['check_login'] = 'login';
        }else{
          $this->pagedata['check_login'] = 'nologin';
        }
        //获取当前管理员设置的金额limited_amount
        $sale_mdl = app::get('b2c')->model('members');
        $office_mdl = app::get('ectools')->model('office'); 
        $detail = $sale_mdl->getList('office_id',array("member_id"=>$member_id));
        $limited_amount = $office_mdl->getList('limited_amount',array("office_id"=>$detail[0][office_id]));
        //判断是否符合管理员设置最低金额的条件
        $this->pagedata['limited_amount'] = $limited_amount[0]['limited_amount'];

        // echo "<pre>";
        // var_dump($this->pagedata['aCart']);
        // exit();

        //add by hyz 2017.11.15 20：13

        // echo "<pre>";

        //获取首批促销打折的商品数量和固定价格
        $gsale_mdl = app::get('b2c')->model('sales_rule_goods');

        foreach ($obj_idents as $key => $value) {
            $promotion[] = $this->pagedata['aCart']['promotion']['goods'][$value];

        }
        foreach ($promotion as $key => $value) {
            $aar[] = $value[0];
        }

        foreach ($aar as $key => $value) {

              // var_dump($value['rule_id']);

              $solution = $gsale_mdl->getList('action_solution',array("rule_id"=>$value['rule_id']));
              
              $from_time[] = $gsale_mdl->getList('from_time',array("rule_id"=>$value['rule_id']));
              // var_dump($from_time[0]["from_time"]);
              $to_time[] = $gsale_mdl->getList('to_time',array("rule_id"=>$value['rule_id']));
              // var_dump($to_time[0]["to_time"]);

              $key=array_keys($solution[0]['action_solution']);
              $tmp= $solution[0]["action_solution"];

              $fltofixed[] = $tmp[$key[0]];

        }
        // var_dump($from_time);
        // var_dump($to_time);
        // var_dump($fltofixed);
        // exit();

        // 促销规则起始时间
        $aar_from = array();
        foreach ($from_time as $key => $value) {
            $aar_from[$key]["from_time"] = $value[0]["from_time"];
        }

        $arr_to = array();
        foreach ($to_time as $key => $value) {
            $arr_to[$key]["to_time"] = $value[0]["to_time"];
        }

        $arr_time = array();
        foreach ($aar_from as $key => $value) {
            $arr_time[$key]['from_time'] = $value['from_time'];
        }

        foreach ($arr_to as $key => $value) {
            $arr_time[$key]['to_time'] = $value['to_time'];
        }
        // var_dump($arr_time);
        // exit();

        $aCart_goods = $this->pagedata['aCart']['object']['goods'];
        foreach ($aCart_goods as $key => $value) {
            //促销限定数量和价格
            $aCart_goods[$key]['fixed'] = $fltofixed[$key];
            //促销起始时间
            $aCart_goods[$key]['ft_time'] = $arr_time[$key];
        }
        // var_dump($aCart_goods);
        // exit();

        $this->pagedata['aCart']['object']['goods'] = $aCart_goods;

        foreach ($aCart_goods as $key => $value) {

            //商品id
            $product_id = $value["obj_items"]["products"][0]["goods_id"];
            //原总额
            $subtotal_prefilter_after = $value['subtotal_prefilter_after'];
            //打折金额
            $discount_amount_prefilter = $value['discount_amount_prefilter'];
            //购买数量
            $squantity = $value['squantity'];
            //促销数量和促销价格
            $fixed = $value['fixed'];
            //促销起始时间
            $ft_time = $value['ft_time'];
            $from_time = $ft_time['from_time'];
            $to_time = $ft_time['to_time'];

            //渠道商等级价格
            $member_lv_price = $value['obj_items']["products"][0]["price"]["member_lv_price"];
            //订货价
            $mlv_price = $value['obj_items']["products"][0]["price"]["mlv_price"];
            
            //统计限制天数范围内已购买的商品数量
            $sql=" select sum(nums) nums from sdb_b2c_order_items a
                         INNER JOIN  sdb_b2c_orders b on a.order_id = b.order_id
                        where b.member_id = ".$member_id ."  and a.goods_id=".$product_id." and b.createtime between  ". strtotime(date('Y-m-d H:i:s', $from_time)) ." and  ". strtotime(date('Y-m-d H:i:s', $to_time)).";";
            $db = kernel::database();
            $nums = $db->select($sql);

            if ($fixed["nums"]) {
            //限量促销

                //如果当前用户在促销期间购买过这个商品，那么计算当前能打折促销的商品的数量
                if($nums[0]['nums']){
                    $fixed["nums"] =$fixed["nums"]  - $nums[0]['nums'];

                    //更新促销打折的商品数量
                    $aCart_goods[$key]['fixed']['nums'] = $fixed["nums"];
                }

                if ($squantity<=$fixed["nums"]) {
                    //打折后的原总额
                    $subtotal_prefilter_after=$fixed["total_amount"]*$squantity;
                }else{        
                   $qq = $squantity-$fixed["nums"];
                   if ($member_lv_price) {
                       $dd = $qq*$member_lv_price;
                       $pp = $member_lv_price;
                   }else{
                       $dd = $qq*$mlv_price;
                       $pp = $mlv_price;
                   }
                   $yy =$fixed["nums"]*$fixed["total_amount"];
                   //打折后的原总额
                   $subtotal_prefilter_after = $dd + $yy;
                }  
            }

            // var_dump($subtotal_prefilter_after);
            //利用sprintf格式化字符串
            $aCart_goods[$key]['subtotal_prefilter_after'] = sprintf("%.2f",$subtotal_prefilter_after);        
        }
        // var_dump($aCart_goods);
        // exit;

        $this->pagedata['aCart']['object']['goods'] = $aCart_goods;
        // echo "<pre>";
        // var_dump($this->pagedata['aCart']['object']['goods']);
        // var_dump($this->pagedata['aCart']['subtotal_prefilter_after']);
        // exit;

        // var_dump($this->pagedata['aCart']);
        // exit;

        // end hyz
        
        $this->page('wap/cart/index.html');
    }

//add by lkb 2015.5.17 发货提示异步查询方法。根据货号和商品数量进行查询
     function ajax_product_goodtips($productid,$val)
    {
        $goodsTipModel=$this->app->model('goods_tips');//goods_tip的实例
        $data=$goodsTipModel->getList('value',array('product_id'=>$productid));//获取商品的发货提示序列
//        $str='暂未设置发货信息';
        $str='无';
        if(empty($data))
            return $str;
        else
        {

            $unserData=unserialize($data[0]['value']);//反序列化
            $order_count=count($unserData);//统计该商品发货提示的条目

       
            /*该段代码处理反序列化后的数组*/
            /*
                原始数组例子:假如开始添加有2条记录，后面第三条是通过编辑功能进行添加的，会出现下面的数组内容
                $userData=array(
                    '0'=>array(
                        'min'=>1,
                        'max'=>500,
                        'title'=>'7天发货'
                    ),
                    '1'=array(
                        'min'=>501,
                        'max'=>1000,
                        'title'=>'14天发货'
                    ),
                    'new_1'=array(
                        'min'=>1001,
                        'max'=>1500,
                        'title'=>'21天发货'
                    )
                );
                序转化为如下数组内容,即将new_1变成2，需要后面根据下表进行遍历
                 $arr=array(
                    '0'=>array(
                        'min'=>1,
                        'max'=>500,
                        'title'=>'7天发货'
                    ),
                    '1'=array(
                        'min'=>501,
                        'max'=>1000,
                        'title'=>'14天发货'
                    ),
                    '2'=array(
                        'min'=>1001,
                        'max'=>1500,
                        'title'=>'21天发货'
                    )
                );

            */

            $row=0;
            foreach ($unserData as $key1 => $value1) {
                foreach ($value1 as $key2 => $value2) {
                    $arr[$row][$key2]=$value2;
                }
                $row++;
                
            }

           /**该商品下的部分发货数量、发货状态、预发货数量**/

           $b2c_order_items=DB_PREFIX."b2c_order_items";
           $b2c_delivery_items=DB_PREFIX."b2c_delivery_items";
           $b2c_orders=DB_PREFIX."b2c_orders";
           $count_out=2;
           $flag=-1;
           //计算部分发货剩下的发货数量
           // $check_goods_num_part="
           //  select 
           //  ($b2c_order_items.nums-$b2c_delivery_items.number) as result1
           //  from
           //  (
           //  $b2c_order_items
           //  inner join 
           //  $b2c_delivery_items
           //  on
           //  $b2c_delivery_items.order_item_id=$b2c_order_items.item_id
           //  )   
           //  inner join 
           //  $b2c_orders
           //  on 
           //  $b2c_orders.order_id=$b2c_order_items.order_id
           //  and 
           //  $b2c_orders.ship_status='2'
           //  and 
           //  $b2c_order_items.product_id='$productid'
           // ";

           // // 计算未发货的数量
           // $check_goods_num="
           // select 
           // $b2c_order_items.nums as result
           // from
           // $b2c_order_items
           // inner join 
           // $b2c_orders
           // on 
           // $b2c_order_items.order_id=$b2c_orders.order_id
           // and 
           // $b2c_orders.ship_status='0'
           // and 
           // $b2c_order_items.product_id='$productid'
           // ";


           $check_goods_num="select sum(a.nums-a.sendnum) as nums
                                from sdb_b2c_order_items a
                                inner join sdb_b2c_orders b on b.order_id=a.order_id
                                where b.ship_status in(0,2) and a.product_id=$productid";
           $temp=kernel::database()->select($check_goods_num);

           // $temp=kernel::database()->select($check_goods_num);
           // $temp1=kernel::database()->select($check_goods_num_part);

           // echo "<pre>";
           // var_dump($temp);
           // var_dump($temp1);
           
            $count_out=$temp?$temp[0]['nums']:0;//计算所以未发货的数量
           // $count_out=$temp[0]['result']+$temp1[0]['result1'];//计算所以未发货的数量

           $all=$count_out+$val; 
           //echo $all;
           $count_out=0;
           $val=0;
           //echo $all;
           //进行区间匹配
           for($i=0;$i<$order_count;$i++)
           {
                if($all>=$arr[$i]['min']&&$all<=$arr[$i]['max'])
                    $flag=$i;
                if($all>$arr[$i]['max'])
                    $flag=$i;
           }
          
            if($flag==-1)
                return $str;
            else
                return $arr[$flag]['title']; 
        }
    }
    //add end
    public function qrCodeAddCart($productId){
        $setting['scanbuy'] = app::get('wap')->getConf('wap.scanbuy');
        $setting['wap_status'] = app::get('wap')->getConf('wap.status');
        if( $setting['scanbuy'] == 'true' && $setting['wap_status'] == 'true' ){
            $goodsData = app::get('b2c')->model('products')->getRow('goods_id',array('product_id'=>$productId));
            $cartData['goods']['goods_id'] = $goodsData['goods_id'];
            $cartData['goods']['product_id'] = $productId;
            $cartData['goods']['num'] = 1;
            $cartData[0] = 'goods';
            $obj_goods = kernel::single('b2c_cart_object_goods');
            $obj_cart_object = kernel::single('b2c_cart_objects');
            $obj_ident = $obj_cart_object->add_object($obj_goods, $cartData, $msg);
            $url = $this->gen_url(array('app'=>'b2c','ctl'=>'wap_cart','act'=>'index'));
            $this->redirect($url);
        }
    }


    //add by lkb 常购清单进入购物车
    public function favoriteAddCart(){
      $productId=$_POST['productId'];
        $setting['scanbuy'] = app::get('wap')->getConf('wap.scanbuy');
        $setting['wap_status'] = app::get('wap')->getConf('wap.status');
        $goodsData = app::get('b2c')->model('products')->getRow('goods_id',array('product_id'=>$productId));
        $cartData['goods']['goods_id'] = $goodsData['goods_id'];
        $cartData['goods']['product_id'] = $productId;
        $cartData['goods']['num'] = 1;
        $cartData[0] = 'goods';
        $obj_goods = kernel::single('b2c_cart_object_goods');
        $obj_cart_object = kernel::single('b2c_cart_objects');
         $obj_ident= $obj_cart_object->add_object($obj_goods, $cartData, $msg);
        if($obj_ident)
        {
          echo '已加入购物车';
        }
        else
        {
          echo '加入购物车失败';
        }
        
    }
    //add end

    //加入购物车 -
    function decCart(){

        //获取当前会员id
        $members=array("member_id"=>kernel::single('b2c_user_object')->get_member_session());
        // $member_id = kernel::single('b2c_user_object')->get_member_id(); 
        // var_dump($members);
        // exit();
        $member_id = $members['member_id'];

        //从请求的数据里获取商品product_id
        $data = $this->_request->get_params(true);

        //获取商品id
        $gid = $data[1];

        // 购物车id
        $obj_ident = "goods_".$gid."_".$gid;

        //首先获取该用户的购物车里的该商品数量
        $sql = "select quantity from sdb_b2c_cart_objects where obj_ident = '$obj_ident' and member_id = '$member_id'";
        $this->db = kernel::database();
        $quantity0 = $this->db->select($sql);
        // echo "<pre>";
        // var_dump($quantity0[0]['quantity']);
        // exit();
        $quantity = $quantity0[0]['quantity'];
        // var_dump($quantity);
        // exit;

        // 商品最小购买数量
            
        $goodsModel = $this->app->model('goods');
        $productsModel = $this->app->model('products');

        $itemProduct = $productsModel->getList('*',array('product_id'=>$gid));
        $goodsId = $itemProduct[0]['goods_id'];

        $aGoodsList = $goodsModel->getList('*',array('goods_id'=>$goodsId));
        $aGoods = $aGoodsList[0];

        $add['isused'] = app::get('b2c')->getConf('system.member.IsUsed');
        $add['pernum'] = app::get('b2c')->getConf('system.product.per.num');

        //个性化批量设置数量
        $add['peradd'] = $aGoods['per_add'];

        if ($add['isused'] == 0) {
          $numb['add'] = $add['peradd'];
        }else{
          $numb['add'] = $add['pernum'];
        }

        // var_dump($this->_request->get_params(true));

        // $this->update();

        //改变商品数量
        if ($quantity) {

          $dec_quantity = $quantity-$numb['add'];

          //弹框中改变购物车数量
          // if($data[2]){
          //     $dec_quantity = $data[2];
          // }
          // print_r($dec_quantity);

          echo '{"success":'.'"'.$dec_quantity.'"'."}";

          $obj_model = $this->app->model('cart_objects');

          if ($dec_quantity > 0) {
            $aa = $obj_model->update( array('quantity'=>$dec_quantity), array('member_id'=>$member_id,'obj_ident'=>$obj_ident) );
          }else{
            $aa =  $obj_model->delete(array('obj_ident'=>$obj_ident,'member_id'=>$member_id));
          }

        }else{
          return false;
        }

    }

    //加入购物车 +
    function addCart(){
        //获取当前会员id
        $members=array("member_id"=>kernel::single('b2c_user_object')->get_member_session());
        // $member_id = kernel::single('b2c_user_object')->get_member_id(); 
        // var_dump($members);
        // exit();
        $member_id = $members['member_id'];

        //从请求的数据里获取商品product_id
        $data = $this->_request->get_params(true);
        // var_dump($data);
        // exit;
        //获取商品id
        $gid = $data[1];

        // 购物车id
        $obj_ident = "goods_".$gid."_".$gid;

        //用户登陆，则获取商品id 会员id，商品信息添加到购物车

        //加到购物车之前判断该商品是否第一次加到购物车，如果不是第一次加到购物车，那么只是更新购物车商品数量，否则是新增商品到购物车

        //首先获取该用户的购物车里的该商品数量
        $sql = "select quantity from sdb_b2c_cart_objects where obj_ident = '$obj_ident' and member_id = '$member_id'";
        $this->db = kernel::database();
        $quantity0 = $this->db->select($sql);
        // echo "<pre>";
        // var_dump($quantity0[0]['quantity']);
        // exit();
        $quantity = $quantity0[0]['quantity'];
        // var_dump($quantity);
        // exit;

        // 商品最小购买数量
            
        $goodsModel = $this->app->model('goods');
        $productsModel = $this->app->model('products');

        $itemProduct = $productsModel->getList('*',array('product_id'=>$gid));
        $goodsId = $itemProduct[0]['goods_id'];

        $aGoodsList = $goodsModel->getList('*',array('goods_id'=>$goodsId));
        $aGoods = $aGoodsList[0];

        //0为开启批量设置数量  1为不开启批量设置数量
        $add['isused'] = app::get('b2c')->getConf('system.member.IsUsed');

        //不开启批量设置数量
        $add['pernum'] = app::get('b2c')->getConf('system.product.per.num');

        // var_dump($add['isused']);
        // exit();

        //个性化批量设置数量
        $add['peradd'] = $aGoods['per_add'];

        if ($add['isused'] == 0) {
          $numb['add'] = $add['peradd'];
        }else{
          $numb['add'] = $add['pernum'];
        }

        // var_dump($data);
        // exit();
        
        // 商品添加到购物车
        $data0 = array(
            'goods' =>array(
                'goods_id' => $gid, 
                'product_id' => $gid,
                'num' => $numb['add']
             ), //商品数量的增量
            'min' => '1', //商品最少数量
            'max' => '84', //商品最大库存
            'mini_cart' => 'true',
             array(0 =>'goods'  )
        );

        // var_dump($data0);
        //弹框中改变购物车数量
        // if($data[2]){
        //   $data0['goods']['num'] = $data[2];
        // }

        // var_dump($data0);
        // echo "<pre>";
        // var_dump($data0);
        // exit();

        $this->add_cart($data0);

        //改变商品数量
        if (!$quantity) {
          //新增商品数量 +1
          $add_quantity = $numb['add'];

          echo '{"success":'.'"'.$add_quantity.'"'."}";
          // $this->splash('success',$add_quantity);
        }else{
          // 如果不是第一次加到购物车，那么只是更新购物车商品数量
          //新增商品数量 +1
          $add_quantity = $quantity+$numb['add'];

          echo '{"success":'.'"'.$add_quantity.'"'."}";
          // $this->splash('success',$add_quantity);
        }

    }

    //手动输入商品数量，添加到购物车
    function entry(){

        //获取当前会员id
        $members=array("member_id"=>kernel::single('b2c_user_object')->get_member_session());
        // $member_id = kernel::single('b2c_user_object')->get_member_id(); 
        // var_dump($members);
        // exit();
        $member_id = $members['member_id'];

        //从请求的数据里获取商品product_id
        $data = $this->_request->get_params(true);
        // var_dump($data);
        // exit;
        //获取商品id
        $gid = $data[1];

        // 购物车id
        $obj_ident = "goods_".$gid."_".$gid;

        $obj_model = $this->app->model('cart_objects');

        $obj_data = $obj_model->getList('*',array('obj_ident'=>$obj_ident));

        // echo "<pre>";
        // var_dump($obj_data);
        // exit();

        //判断是否第一次添加到购物车
        if ($obj_data) {

          //在加入购物车之前，先检查商品库存
          $sql = "select store from sdb_b2c_products where product_id = ".$gid;
          $this->db = kernel::database();
          $store = $this->db->select($sql);
          $goods_store = $store[0]['store'];
          // var_dump($store[0]['store']);
          // var_dump($goods_store);
          // var_dump($data[2]);
          // exit();
          $dd = intval($data[2]);

          //如果购买商品数量大于商品库存
          if($dd > $goods_store) {
            echo '{"error":'.'"购买数量超出库存"'.'}';
            return false;

          }else{

            $obj_model->update( array('quantity'=>$data[2]), array('member_id'=>$member_id,'obj_ident'=>$obj_ident) );

            echo '{"success":'.'"'.$data[2].'"'."}";

          }
          
        }else{

          // 商品添加到购物车
          $data0 = array(
              'goods' =>array(
                  'goods_id' => $gid, 
                  'product_id' => $gid,
                  'num' => $data[2]
               ), //商品数量的增量
              'min' => '1', //商品最少数量
              'max' => '84', //商品最大库存
              'mini_cart' => 'true',
               array(0 =>'goods'  )
          );

          $this->add_cart($data0);
          echo '{"success":'.'"'.$data[2].'"'."}";

        }

    }

    //加入购物车改造方法（post改为传入参数）
    function add_cart($data,$type='goods'){

        /**
         * 处理信息和验证过程
         * servicelist('b2c_cart_object_apps')=>
         * gift_cart_object_gift
         * b2c_cart_object_coupon
         * b2c_cart_object_goods
         */
        $arr_objects = array();
            if ($objs = kernel::servicelist('b2c_cart_object_apps'))
        {
            foreach ($objs as $obj)
            {
                if ($obj->need_validate_store()){
                    $arr_objects[$obj->get_type()] = $obj;
                }
            }
        }

        //商品类型 商品id
        //$data = $this->_request->get_params(true);

        if($data['response_json'] == 'true'){//ajax提交返回错误
            $errorRequest = true;
        }
         
        /**
         * 处理校验各自的数据是否可以加入购物车
         */
     
         //预售商品进入购物车的判断
        $prepare=kernel::service('prepare_goods');
        // echo "<pre>";
        // var_dump($prepare);
        // exit();
        if($prepare)
        {
            $pre=$prepare->get_product_type($data);
            foreach ($pre as $key => $value) {
                $prep[] = $value['promotion_type'];
            }
            if (!empty($pre))
            {
                $msg = app::get('b2c')->_('预售商品不能加入购物车！');
                if($post['mini_cart']&&in_array('prepare', $prep)){
                    $this->pagedata['errormsg'] = $msg;
                    $this->page('site/cart/mini_cart_error.html', true);
                    return;
                } else {
                    $this->splash('error',$url,$msg,$errorRequest);
                }
            }
        }
        
        ///////////////////////
        if (!$arr_objects[$type])
        {
            $msg = app::get('b2c')->_('商品类型错误！');
            if($_POST['mini_cart']){
                $this->splash('error',null,$msg);
            } else {
                $fail_url = $arr_objects[$type]->get_fail_url($data);
                $this->splash('false',$fail_url,$msg,'','',true);
            }
        }
        if (method_exists($arr_objects[$type], 'get_data'))
        {
            if (!$aData = $arr_objects[$type]->get_data($data,$msg))
            {
                if($_POST['mini_cart']){
                    $this->splash('error',null,$msg);
                    echo json_encode( array('error'=>$msg) );exit;    // test hzk
                } else {
                    $fail_url = $arr_objects[$type]->get_fail_url($data);
                    $this->splash('error',$fail_url,$msg,'','',true);
                }
            }
        }
        $aData['apply_platform'] = '1';
             //echo $data['goods']['num'];exit;
       // echo '<pre>';
       // var_dump($data);
       // exit;
       // echo '-=---=-=-=';
        //  @mo 2017年5月2日 09:17:18 这里添加控制当前商品在满赠促销的规则下是否可以加入购物车
        //这段代码位置要放到aData之后，由于立即购买按钮和加入购物车按钮同时使用，太前导致无法获得aData数据。可能导致立即购买后空白页出现
         $member_id = kernel::single('b2c_user_object')->get_member_id();
         if(!empty($member_id) && $aData['btype'] != 'is_fastbuy')
         {
            $checkoutproduct = kernel::single('b2c_checkproduct_check');
            //判断当前商品是否存在相对应的满赠促销规则
            $products_promotion = $checkoutproduct->get_gift_of_full_promotion($data['goods']['goods_id']);
            if(!empty($products_promotion))
            {
                  $is_in_ofiice_memberlvid = $checkoutproduct->office_member_in($products_promotion,$member_id);
                if($is_in_ofiice_memberlvid)
                {
                     $product_id = (int)$data['goods']['product_id'];
                    $product_quantity = $checkoutproduct->get_product_quantity_from_cart($data['goods']['product_id']);
                    $canbuy = 0;
                    $canbuy = $checkoutproduct->canaddtocart($product_id,$product_quantity,(int)$data['goods']['num']);
                //这里是控制商品详情页的加入购物车的限制  当 echo  1 的时候 会提示超过购买限制  by hzk
                    //kernel::single('b2c_ctl_site_product')->index();
//                    if($canbuy == -1 || $canbuy == -2 )
//                    {
//                          echo 1;exit;   // test hzk
//                    }
                }
            }
           
         }
        // 进行各自的特殊校验
        if (method_exists($arr_objects[$type], 'check_object'))
        {


            if (!$arr_objects[$type]->check_object($aData,$msg))
            {
                if($_POST['mini_cart']){
                    $this->splash('error',null,$msg);
                } else {
                    $fail_url = $arr_objects[$type]->get_fail_url($data);
                    $this->splash('error',$fail_url,$msg,'','',true);
                }
            }
        }
        $obj_cart_object = kernel::single('b2c_cart_objects');
        // var_dump($arr_objects[$type]);
        // var_dump($aData);
        // var_dump($msg);
        // exit;
        if (!$obj_cart_object->check_store($arr_objects[$type], $aData, $msg))
        {
            if($_POST['mini_cart']){
                $this->splash('error',null,$msg,'','',true);
            } else {
                $fail_url = $arr_objects[$type]->get_fail_url($data);
                $this->splash('error',$fail_url,$msg,'','',true);
            }
        }
        /** end **/
        //快速购买
        if(isset($aData[1]) && $aData[1] == 'quick' && empty($this->member_status)){
            $this->splash('success',$this->gen_url(array('app'=>'b2c','ctl'=>'wap_cart','act'=>'checkout')));
        }

        if($aData['btype'] == 'is_fastbuy'){
          $member_id = kernel::single('b2c_user_object')->get_member_id();
         if(!empty($member_id) )
         {
            $checkoutproduct = kernel::single('b2c_checkproduct_check');
            //判断当前商品是否存在相对应的满赠促销规则
            $products_promotion = $checkoutproduct->get_gift_of_full_promotion($data['goods']['goods_id']);
            if(!empty($products_promotion))
            {
                  $is_in_ofiice_memberlvid = $checkoutproduct->office_member_in($products_promotion,$member_id);
                if($is_in_ofiice_memberlvid)
                {
                     $product_id = (int)$data['goods']['product_id'];
                    $product_quantity = $checkoutproduct->get_product_quantity_from_cart($data['goods']['product_id']);
                    $canbuy = 0;
                    $canbuy = $checkoutproduct->canaddtocart($product_id,$product_quantity,(int)$data['goods']['num']);
                  
                    //kernel::single('b2c_ctl_site_product')->index();
                    
                    
//                    if($canbuy == -1 || $canbuy == -2 )
//                    {
//                          //return;
//                    }
                }
            }
           
         }
         
            $obj_ident = $obj_cart_object->add_object($arr_objects[$type], $aData, $msg,true);
        }else{
            $obj_ident = $obj_cart_object->add_object($arr_objects[$type], $aData, $msg);
        }

        if(!$obj_ident){
            if($_POST['mini_cart']){
                $this->pagedata['errormsg'] = $msg;
                $this->page('site/cart/mini_cart_error.html', true);
                return;
            } else {
                $this->splash('error',$url,$msg,'','',$data['response_type']);
            }
        } else {
            if(isset($aData['btype']) && $aData['btype'] == 'is_fastbuy') {
                $this->_check_checkout('true');
            }else{
                if($_POST['mini_cart']){
                    $arr = $this->app->model("cart")->get_objects();
                    $temp = $arr['_cookie'];
                    $this->pagedata['cartCount']      = $temp['CART_COUNT'];
                    $this->pagedata['cartNumber']     = $temp['CART_NUMBER'];
                    $this->pagedata['cartTotalPrice'] = $temp['CART_TOTAL_PRICE'];
                    $this->page('wap/cart/mini_cart.html', true);
                    return;
                }
                // coupon
                if($aData[0]=='coupon'){
                    if (!$data['response_type']){
                        $url = array('app'=>'b2c', ctl=>'wap_cart','act'=>'checkout');
                        $this->redirect( $url );
                    }else{
                        $this->_common(1,$aData['is_fastbuy']);
                        //只输出能够使用的优惠劵信息
                        $return_coupon_data = array();
                        foreach($this->pagedata['aCart']['object']['coupon'] as $key=>$coupon_data){
                            if($coupon_data['used'] == 'true'){
                                $return_coupon_data[$key]['coupon'] = $coupon_data['coupon'];
                                $return_coupon_data[$key]['cpns_id'] = $coupon_data['cpns_id'];
                                $return_coupon_data[$key]['name'] = $coupon_data['name'];
                                $return_coupon_data[$key]['obj_ident'] = $coupon_data['obj_ident'];
                            }
                        }
                        if($return_coupon_data){
                            $arr_json_data = array(
                                'success'=>app::get('b2c')->_('优惠券使用成功！'),
                                'data'=>$return_coupon_data,
                                'md5_cart_info'=>kernel::single('b2c_cart_objects')->md5_cart_objects(),
                            );
                            echo json_encode($arr_json_data);exit;   // test hzk
                        }else{
                            $ident = 'coupon_'.$aData['coupon'];
                            $this->app->model('cart_objects')->remove_object('coupon', $ident, $msg);
                            $url = array('app'=>'b2c', ctl=>'wap_cart','act'=>'checkout');
                            $this->splash('error',$url,'优惠券使用失败！','','',true);
                        }
                    }
                } else {
                    $url = $this->gen_url(array('app'=>'b2c', ctl=>'wap_cart'));
                    // $this->splash('success',$url);
                }
            }
        }
    }
    // 添加
    public function add($type='goods') {

        // echo '<pre>';
        // var_dump($_POST);
        // exit; 

        /**
         * 处理信息和验证过程
         * servicelist('b2c_cart_object_apps')=>
         * gift_cart_object_gift
         * b2c_cart_object_coupon
         * b2c_cart_object_goods
         */
        $arr_objects = array();
            if ($objs = kernel::servicelist('b2c_cart_object_apps'))
        {
            foreach ($objs as $obj)
            {
                if ($obj->need_validate_store()){
                    $arr_objects[$obj->get_type()] = $obj;
                }
            }
        }

        //商品类型 商品id
        $data = $this->_request->get_params(true);

        // echo '<pre>';
        // var_dump($data);
        // exit; 

        if($data['response_json'] == 'true'){//ajax提交返回错误
            $errorRequest = true;
        }  
        /**
         * 处理校验各自的数据是否可以加入购物车
         */
     
         //预售商品进入购物车的判断
        $prepare=kernel::service('prepare_goods');
        // echo "<pre>";
        // var_dump($prepare);
        // exit();
        if($prepare)
        {
            $pre=$prepare->get_product_type($data);
            foreach ($pre as $key => $value) {
                $prep[] = $value['promotion_type'];
            }
            if (!empty($pre))
            {
                $msg = app::get('b2c')->_('预售商品不能加入购物车！');
                if($post['mini_cart']&&in_array('prepare', $prep)){
                    $this->pagedata['errormsg'] = $msg;
                    $this->page('site/cart/mini_cart_error.html', true);
                    return;
                } else {
                    $this->splash('error',$url,$msg,$errorRequest);
                }
            }
        }
        
        ///////////////////////
        if (!$arr_objects[$type])
        {
            $msg = app::get('b2c')->_('商品类型错误！');
            if($_POST['mini_cart']){
                $this->splash('error',null,$msg);
            } else {
                $fail_url = $arr_objects[$type]->get_fail_url($data);
                $this->splash('false',$fail_url,$msg,'','',true);
            }
        }
        if (method_exists($arr_objects[$type], 'get_data'))
        {
            if (!$aData = $arr_objects[$type]->get_data($data,$msg))
            {
                if($_POST['mini_cart']){
                    $this->splash('error',null,$msg);
                    echo json_encode( array('error'=>$msg) );exit;    // test hzk
                } else {
                    $fail_url = $arr_objects[$type]->get_fail_url($data);
                    $this->splash('error',$fail_url,$msg,'','',true);
                }
            }
        }
        $aData['apply_platform'] = '1';

        // var_dump($data['btype']);
        // exit();

        //加入购物车 详细商品中的购物车添加总数量减去已存入购物车数量
        if (!$data['btype']) {

            // echo '<pre>';
            // var_dump($_POST);
            // exit; 

           $arrMember = kernel::single('b2c_user_object')->get_current_member();
           $member_id = $arrMember['member_id'];
           $obj_ident = "goods_".$data['goods']['goods_id']."_".$data['goods']['goods_id'];
           $this->db = kernel::database();
           $gsql = "select quantity from sdb_b2c_cart_objects where obj_ident = '$obj_ident' and member_id = '$member_id'";
           $quantity0 = $this->db->select($gsql);
           $aData['goods']['num'] = $aData['goods']['num'] - $quantity0[0]['quantity'];

        }

        // echo '<pre>';
        // var_dump($aData['goods']['num']);
        // exit; 

        //如果选择商品数量为0，那么提示选择添加商品
        if ($aData['goods']['num']==0) {
          // echo '<pre>';
          // var_dump($aData['goods']['num']);
          // exit; 

          // echo "请添加商品数量！";
          exit();
        }
        
       // echo '<pre>';
       // var_dump($data);
       // var_dump($aData);
       // exit;
        //  @mo 2017年5月2日 09:17:18 这里添加控制当前商品在满赠促销的规则下是否可以加入购物车
        //这段代码位置要放到aData之后，由于立即购买按钮和加入购物车按钮同时使用，太前导致无法获得aData数据。可能导致立即购买后空白页出现
         $member_id = kernel::single('b2c_user_object')->get_member_id();
         if(!empty($member_id) && $aData['btype'] != 'is_fastbuy')
         {
            $checkoutproduct = kernel::single('b2c_checkproduct_check');
            //判断当前商品是否存在相对应的满赠促销规则
            $products_promotion = $checkoutproduct->get_gift_of_full_promotion($data['goods']['goods_id']);
            if(!empty($products_promotion))
            {
                  $is_in_ofiice_memberlvid = $checkoutproduct->office_member_in($products_promotion,$member_id);
                if($is_in_ofiice_memberlvid)
                {
                     $product_id = (int)$data['goods']['product_id'];
                    $product_quantity = $checkoutproduct->get_product_quantity_from_cart($data['goods']['product_id']);
                    $canbuy = 0;
                    $canbuy = $checkoutproduct->canaddtocart($product_id,$product_quantity,(int)$data['goods']['num']);
                //这里是控制商品详情页的加入购物车的限制  当 echo  1 的时候 会提示超过购买限制  by hzk
                    //kernel::single('b2c_ctl_site_product')->index();
//                    if($canbuy == -1 || $canbuy == -2 )
//                    {
//                          echo 1;exit;   // test hzk
//                    }
                }
            }
           
         }
        // 进行各自的特殊校验
        if (method_exists($arr_objects[$type], 'check_object'))
        {


            if (!$arr_objects[$type]->check_object($aData,$msg))
            {
                if($_POST['mini_cart']){
                    $this->splash('error',null,$msg);
                } else {
                    $fail_url = $arr_objects[$type]->get_fail_url($data);
                    $this->splash('error',$fail_url,$msg,'','',true);
                }
            }
        }
        $obj_cart_object = kernel::single('b2c_cart_objects');
        // var_dump($arr_objects[$type]);
        // var_dump($aData);
        // var_dump($msg);
        // exit;
        if (!$obj_cart_object->check_store($arr_objects[$type], $aData, $msg))
        {
            if($_POST['mini_cart']){
                $this->splash('error',null,$msg,'','',true);
            } else {
                $fail_url = $arr_objects[$type]->get_fail_url($data);
                $this->splash('error',$fail_url,$msg,'','',true);
            }
        }
        /** end **/
        //快速购买
        // var_dump($aData[1]);
        // exit();
        if(isset($aData[1]) && $aData[1] == 'quick' && empty($this->member_status)){
            $this->splash('success',$this->gen_url(array('app'=>'b2c','ctl'=>'wap_cart','act'=>'checkout')));
        }

        // var_dump($aData['btype']);
        // exit();

        if($aData['btype'] == 'is_fastbuy'){
          $member_id = kernel::single('b2c_user_object')->get_member_id();

          // var_dump($member_id);
          // exit;

         if(!empty($member_id) )
         {
            $checkoutproduct = kernel::single('b2c_checkproduct_check');
            // var_dump($checkoutproduct);
            // exit;

            //判断当前商品是否存在相对应的满赠促销规则
            $products_promotion = $checkoutproduct->get_gift_of_full_promotion($data['goods']['goods_id']);

            // var_dump($products_promotion);
            // exit();

            if(!empty($products_promotion))
            {
                  $is_in_ofiice_memberlvid = $checkoutproduct->office_member_in($products_promotion,$member_id);
                if($is_in_ofiice_memberlvid)
                {
                     $product_id = (int)$data['goods']['product_id'];
                    $product_quantity = $checkoutproduct->get_product_quantity_from_cart($data['goods']['product_id']);
                    $canbuy = 0;
                    $canbuy = $checkoutproduct->canaddtocart($product_id,$product_quantity,(int)$data['goods']['num']);
                  
                    //kernel::single('b2c_ctl_site_product')->index();
                                    
//                    if($canbuy == -1 || $canbuy == -2 )
//                    {
//                          //return;
//                    }
                }
            }
           
         }
            //购物车商品id goods_1702393_1702393
            $obj_ident = $obj_cart_object->add_object($arr_objects[$type], $aData, $msg,true);

            // var_dump($obj_ident);
            // exit();
        }else{
            $obj_ident = $obj_cart_object->add_object($arr_objects[$type], $aData, $msg);
        }

        if(!$obj_ident){
            if($_POST['mini_cart']){
                $this->pagedata['errormsg'] = $msg;
                $this->page('site/cart/mini_cart_error.html', true);
                return;
            } else {
                $this->splash('error',$url,$msg,'','',$data['response_type']);
            }
        } else {

            // var_dump($aData['btype']);
            // exit();

            //立即订购
            if(isset($aData['btype']) && $aData['btype'] == 'is_fastbuy') {
                // echo "123";
                // exit;
                $this->_check_checkout('true');
            }else{
                if($_POST['mini_cart']){
                    $arr = $this->app->model("cart")->get_objects();
                    $temp = $arr['_cookie'];
                    $this->pagedata['cartCount']      = $temp['CART_COUNT'];
                    $this->pagedata['cartNumber']     = $temp['CART_NUMBER'];
                    $this->pagedata['cartTotalPrice'] = $temp['CART_TOTAL_PRICE'];
                    $this->page('wap/cart/mini_cart.html', true);
                    return;
                }
                // coupon
                if($aData[0]=='coupon'){
                    if (!$data['response_type']){
                        $url = array('app'=>'b2c', ctl=>'wap_cart','act'=>'checkout');
                        $this->redirect( $url );
                    }else{
                        $this->_common(1,$aData['is_fastbuy']);
                        //只输出能够使用的优惠劵信息
                        $return_coupon_data = array();
                        foreach($this->pagedata['aCart']['object']['coupon'] as $key=>$coupon_data){
                            if($coupon_data['used'] == 'true'){
                                $return_coupon_data[$key]['coupon'] = $coupon_data['coupon'];
                                $return_coupon_data[$key]['cpns_id'] = $coupon_data['cpns_id'];
                                $return_coupon_data[$key]['name'] = $coupon_data['name'];
                                $return_coupon_data[$key]['obj_ident'] = $coupon_data['obj_ident'];
                            }
                        }
                        if($return_coupon_data){
                            $arr_json_data = array(
                                'success'=>app::get('b2c')->_('优惠券使用成功！'),
                                'data'=>$return_coupon_data,
                                'md5_cart_info'=>kernel::single('b2c_cart_objects')->md5_cart_objects(),
                            );
                            echo json_encode($arr_json_data);exit;   // test hzk
                        }else{
                            $ident = 'coupon_'.$aData['coupon'];
                            $this->app->model('cart_objects')->remove_object('coupon', $ident, $msg);
                            $url = array('app'=>'b2c', ctl=>'wap_cart','act'=>'checkout');
                            $this->splash('error',$url,'优惠券使用失败！','','',true);
                        }
                    }
                } else {
                    $url = $this->gen_url(array('app'=>'b2c', ctl=>'wap_cart'));
                    $this->splash('success',$url);
                }
            }
        }
    }
   //根据用户获取购物数量返回给首页
   public function getcart_data(){
     $member_id = kernel::single('b2c_user_object')->get_member_id();
     $sql = "select obj_ident,quantity from sdb_b2c_cart_objects where member_id = '$member_id' ";
      $this->db = kernel::database();
      $quantity0 = $this->db->select($sql);
      foreach ($quantity0 as $key => $value) {
        $goods_id = explode("_",$value['obj_ident']);
        $quantity0[$key]['obj_ident'] = $goods_id[2];
      }
   echo json_encode($quantity0);
   }

    // 修改 - 完全数据
    public function update() {
      // echo "456";
      //   exit();
        $msg = "";
        $this->update_cart($msg);
        
        /** 完全数据 **/
        $this->_cart_main($msg);
        }


    /** 最小数据的修改对应的控制器 **/
    public function updateMiniCart() {
        $this->update_cart($msg,'mini');
        /** 最小数据 **/
        $this->_cart_main($msg,'mini');
    }

    /** 中等数据购物车修改控制器方法 **/
    public function update_middle() {
        $this->update_cart($msg,'middle');
        /** 中等数据 **/
        $this->_cart_main($msg,'middle');
    }

    /**
     * 修改购物车的方法-私有，只处理数据
     * @param string error message
     * @param string json type
     * @return null
     */
    private function update_cart(&$msg='',$type='all') {
        $aParams = $this->_request->get_params(true);
        // logger::info('hyz:'.var_export($aParams,true));
        $mCartObject = $this->app->model('cart_objects');
        $aCart = $this->mCart->get_basic_objects();
        foreach($aCart as $row)
        {
             if( isset($aParams['modify_quantity'][$row['obj_ident']]) )
             {
                $update_row = $row;
                break;
             }
        }
        if($aParams['modify_quantity'] && is_array($aParams['modify_quantity'])){
            $view = "";
            switch ($type){
                case 'mini':
                    $view = "wap/cart/mini_index.html";
                break;
                case 'middle':
                    $view = "wap/cart/middle_index.html";
                break;
                case 'all':
                default:
                    $view = "wap/cart/index.html";
                break;
            }

            foreach ($aParams['modify_quantity'] as $obj_ident=>$arr_object){
             $temp = $aParams['modify_quantity'][$obj_ident];
             $flag = $this->_v_cart_object($temp, $update_row, false);
                $arr_object['quantity'] = (float)$arr_object['quantity'];
                $_flag = $mCartObject->update_object( $aParams['obj_type'],$obj_ident,$arr_object );

                    if( is_array($_flag) && isset($_flag['status']) && isset($_flag['msg']) ) {
                            if( $_flag['status'] ) {
                                $this->ajax_update = true;
                        $this->update_obj_ident['ident'] = $obj_ident; //值不同。修改 失败直接推出循环
                        $msg = $_flag['msg'];
                    } else {
                        $error_json = array(
                            'error'=>$_flag['msg'],
                        );
                        $this->pagedata = $error_json;
                        $this->page($view);
                    }
                } else {
                    if( !$_flag ) {
                        $error_json = array(
                            'error'=>app::get('b2c')->_('购物车修改失败！'),
                        );
                        $this->pagedata = $error_json;
                        $this->page($view);
                    } else {
                        $this->ajax_update = true;
                        $this->update_obj_ident['ident'] = $obj_ident; //值不同。修改 失败直接推出循环
                        $msg = app::get('b2c')->_('购物车修改成功！');
                    }
                }
            }
        }
    }

    // add by hzy 2017.11.21 清空购物车
    public function remove_cart()
    {
        $member_id = kernel::single('b2c_user_object')->get_member_id();

        $flag =  app::get('b2c')->model('cart_objects')->delete(array('member_id'=>$arrMember['member_id']));

        if ($flag==true) {
            echo '{"success":"清空成功"}';
            // $view = "wap/cart/index.html";
        }else{
            echo '{"success":"清空失败"}';
        }

        // $this->page($view);   

    }
    //add end


    // 删除&清空
    public function remove() {
        $msg = '';
        $this->remove_cart_object($msg);

        $this->_cart_main($msg);
    }

    // 删除优惠券 优惠券移动到checkout
    public function removeCartCoupon() {
        $msg = '';
        $this->remove_cart_object($msg,'coupon');

        $this->_cart_main($msg,'coupon');
    }

    // 删除&清空 迷你购物车删除商品接口
    public function removeMiniCart() {
        $msg = '';
        $this->remove_cart_object($msg,'mini');

        $this->_cart_main($msg,'mini');
    }

    // 返回中等数据的删除机制
    public function remove_middle() {
        $msg = '';
        $this->remove_cart_object($msg,'middle');

        $this->_cart_main($msg,'middle');
    }

    /**
     * 删除购物车的方法
     * @param string message
     * @param string json type
     * @return null
     */
    private function remove_cart_object(&$msg='',$type='all'){
        $aParams = $this->_request->get_params(true);
        $mCartObject = $this->app->model('cart_objects');
        $this->ajax_html = true;  //用于返回页面识别。当无商品是跳转至cart_empty

        $view = "";
        switch ($type){
            case 'mini':
                $view = "wap/cart/mini_index.html";
            break;
            case 'middle':
                $view = "wap/cart/middle_index.html";
            break;
            case 'all':
            default:
                $view = "wap/cart/index.html";
            break;
    }

        if ($aParams[0] == 'coupon'){
            $ident = $aParams['cpn_ident'];

            $flag = $mCartObject->remove_object('coupon', $ident, $msg);
            if( !$flag ){
                $error_json = array(
                    'error'=>$msg,
                );
                $this->pagedata = $error_json;
                $this->page($view);
            }
        }else{
        // 清空购物车
        //H5端删除购物车出现删除一个会全部清空，所以隐藏一下代码和加判断!empty($obj_ident)没有商品id就不能删除购物车数据
        if($aParams[0] == 'all' || empty($aParams['modify_quantity'])) {
            // $obj_type = null;
            //     if (!$mCartObject->remove_object('', null, $msg)){
            //         // 不带入参清空所有的
            //         $error_json = array(
            //             'error'=>$msg,
            //         );
            //         $this->pagedata = $error_json;
            //         $this->page($view);
            //     }
        } else {
                // 删除单一商品.
                if($aParams['modify_quantity'] && is_array($aParams['modify_quantity'])){
                    foreach ($aParams['modify_quantity'] as $obj_ident=>$arr_object){
                        if ($arr_object['quantity']&& !empty($obj_ident)){
                            // 删除整个商品对象.
                            if (!$mCartObject->remove_object($aParams['obj_type'], $obj_ident, $msg)){
                                $error_json = array(
                                    'error'=>$msg,
                                );
                                $this->pagedata = $error_json;
                                $this->page($view);
                    }
                        }else{
                            // 删除购物车对象中的附属品，配件和赠品等.
                            foreach ($arr_object as $obj_type=>$arr_quantity){
                                if (!$mCartObject->remove_object_part($obj_type, $obj_ident, $arr_quantity, $msg)){
                                    $error_json = array(
                                        'error'=>$msg,
                                    );
                                    $this->pagedata = $error_json;
                                    $this->page($view);
            }
        }
    }
                        }
                    }
                }
        }
    }

    public function remove_cart_to_disabled() {
        $_obj_type  = $this->_request->get_param(0);
        $_obj_ident  = $this->_request->get_param(1);
        $_product_id = (int)$this->_request->get_param(2);
        $_SESSION['cart_objects_disabled_item'][$_obj_type][$_obj_ident]['gift'][$_product_id] = 'true';
        $this->_response->set_http_response_code(404);return;
    }


    //立即订购
    public function _check_checkout($isfastbuy=0){

        // echo "456";
        // exit();

        // var_dump($this->member_status);
        // exit();

        //判断登陆状态
        if (!$this->member_status){
          if($isfastbuy){
            $url = $this->gen_url(array('app'=>'b2c','ctl'=>'wap_cart','act'=>'loginBuy','arg0'=>'true'));
            $this->splash('success',$url,'需要登录才能购买...','','',true);
          }else{
            $url = $this->gen_url(array('app'=>'b2c','ctl'=>'wap_cart','act'=>'loginBuy'));
            $this->splash('success',$url,'需要登录才能购买...','','',true);
          }
        }
        // 初始化购物车数据
        $this->_common(false,$isfastbuy);

        // echo "<pre>";
        // var_dump($this->_common());
        // exit();

        $this->begin(array('app'=>'b2c','ctl'=>'wap_cart','act'=>'index'));

        // var_dump($this->pagedata['is_empty']);
        // exit();

        // 购物车是否为空
        if ($this->pagedata['is_empty'])
        {   
            // echo "23";
            // exit();
            $this->end(false, app::get('b2c')->_('购物车为空！'));
        }

        // echo "456";
        // exit();

        // 购物是否满足起订量和起订金额
        if ((isset($this->pagedata['aCart']['cart_status']) && $this->pagedata['aCart']['cart_status'] == 'false') && (isset($this->pagedata['aCart']['cart_error_html']) && $this->pagedata['aCart']['cart_error_html'] != ""))
        {
            $this->end(false, $this->pagedata['aCart']['cart_error_html']);
        }

        // $this->redirect($this->gen_url(array('app'=>'b2c','ctl'=>'wap_cart','act'=>'checkout','arg0'=>$isfastbuy)));
        $this->splash('success',$this->gen_url(array('app'=>'b2c','ctl'=>'wap_cart','act'=>'checkout','arg0'=>$isfastbuy)),'去结算...','','',true);
    }

    /**
     * checkout
     * 切记和admin/order:create保持功能上的同步
     *
     * @access public
     * @return void
     */
    public function checkout($isfastbuy=0)
    {   

        // echo "489";
        // exit;

        //获取不到商品数量

        // echo "<pre>789";
        // var_dump($_POST);
        // exit;

        /**
         * 取到扩展参数
         */
        $arr_args = func_get_args();
        $arr_args = array(
            'get' => $arr_args,
            'post' => array('modify_quantity'=>$_POST['modify_quantity']),
        );

        // var_dump($arr_args);
        // exit;

        $arr_args = utils::_RemoveXSS($arr_args);
        $this->pagedata['json_args'] = json_encode($arr_args);
        if($isfastbuy){
            $this->pagedata['is_fastbuy'] = $isfastbuy;
        }else{
            $this->pagedata['is_fastbuy'] = false;
        }

        if (!$this->member_status){
          if($isfastbuy){
            $url = $this->gen_url(array('app'=>'b2c','ctl'=>'wap_cart','act'=>'loginBuy','arg0'=>'true'));
            $this->splash('success',$url,app::get('b2c')->_('还未登录，请先登录'));
          }else{
           // $url = $this->gen_url(array('app'=>'b2c','ctl'=>'wap_cart','act'=>'loginBuy'));
           // $this->splash('success',$url,'','',0);
            $this->redirect(array('app'=>'b2c','ctl'=>'wap_cart','act'=>'loginBuy'));
          }
        }
        // 初始化购物车数据
        $this->_common(false,$isfastbuy);
        $this->begin(array('app'=>'b2c','ctl'=>'wap_cart','act'=>'index'));

        // 购物车是否为空
        if ($this->pagedata['is_empty'])
        {
            $this->end(false, app::get('b2c')->_('购物车为空！'));
        }
        // 结算购物车时判断数据库是否满足购物车数量
        foreach ($this->pagedata['aCart']['object']['goods'] as $key => $value) {
            $quantity1 = app::get('b2c')->model('cart_objects')->getList('*',array('obj_ident'=>$value['obj_ident'],'member_id'=>$arrMember['member_id']));
            $freez = app::get('b2c')->model('products')->getList('*',array('product_id'=>$value['params']['product_id']));
            if(($freez[0]['store']-$freez[0]['freez'])<$quantity1[0]['quantity']){
            $this->end(false, app::get('b2c')->_('商品').$value['store']['name'].app::get('b2c')->_('库存不足'));
          }
        }
        // 购物是否满足起订量和起订金额
        if ((isset($this->pagedata['aCart']['cart_status']) && $this->pagedata['aCart']['cart_status'] == 'false') && (isset($this->pagedata['aCart']['cart_error_html']) && $this->pagedata['aCart']['cart_error_html'] != ""))
        {
            $this->end(false, $this->pagedata['aCart']['cart_error_html']);
        }
     //    echo "<pre>";
     // var_dump($this->pagedata['aCart']);
        $this->checkout_result($isfastbuy);
    }


////////////////////结算移动端判断
    /*
    @mo
     
        返回当前购物车满足促销条件type为满足促销的促销规则

     */
    public function check_fullofgift($aCart = array())
    {
         $all_rules = array();
        $pre_rule = app::get('b2c')->model('sales_rule_order');
        if(!empty($aCart['promotion']['order']))
        {
            foreach ($aCart['promotion']['order'] as $key => $value) {
            $filter_c = array('rule_id|nequal'=>$value['rule_id']);
             $one_rules = $pre_rule->getList('rule_id,conditions,from_time,to_time,name', $filter_c, 0, -1, 'rule_id ASC');
             //筛选出condition type2为Fullofgifts(满赠促销 购买限制最大购买数量)
             if($one_rules[0]['conditions']['conditions'][0]['type2'] == app::get('b2c')->_('Fullofgifts'))
             {
               
                Array_push($all_rules, $one_rules[0]); 
             }
        }
        }
        
        return $all_rules;
    }

    /*
        根据输入的goods_id获取当前商品在购物车中的数量
     */
    public function get_goods_quantity_form_cart($goods_id,$aCart = array())
    {
        if(empty($aCart)) return 0;
     
        foreach ($aCart['object']['goods'] as $key => $value) {
           if($value['obj_items']['products'][0]['goods_id'] == $goods_id)
           {
             return   $value['quantity'];
           }
           
        }
    }
    /*
     @mo
             根据当前fulloftype 来判断当前购物车里的商品是否符合促销条件的限制个数

     */
    public function is_fit_to_order($promotion_fullofgifts,$aCart = array())
    {
        $buy = app::get('b2c')->_('canbuy');
        if(empty($aCart) || empty($promotion_fullofgifts)) return $buy;
    
        foreach ($promotion_fullofgifts as $key => $the_rule) {
            //最大购买数量
            //$the_rule['conditions']['conditions'][0]['maxquantity'];
            //商品号
            //$the_rule['conditions']['conditions'][0]['conditions'][0]['value'];

            $had_buy_this_goods_quantity = $this->get_number_from_rule_in_order($the_rule);
            //目前可以购买的个数
 
            $now_can_buy_this_goods_quantity = $the_rule['conditions']['conditions'][0]['maxquantity'] -$had_buy_this_goods_quantity;
            //当前这个商品在购物车的个数
            $pre_this_goods_in_cart_quantity = $this->get_goods_quantity_form_cart($the_rule['conditions']['conditions'][0]['conditions'][0]['value'],$aCart);

            if($now_can_buy_this_goods_quantity <  $pre_this_goods_in_cart_quantity)
            {
                 $buy = app::get('b2c')->_('cannotbuy');
                return $buy;//意味某个商品数量超过限制
            }
         
        }
        return $buy;
    }
    /*
        @mo
        根据促销规则，返回在促销条件过程中会员所购买该商品的数量(只包含促发了促销条件的个数)
     */
    public function get_number_from_rule_in_order($rule_protion)
    {

           $member_id = kernel::single('b2c_user_object')->get_member_id();

            $db_order = app::get('b2c')->model('orders');

             $fromtime = $rule_protion['from_time'];
             $totime = $rule_protion['to_time'];
               
             $filter = array('member_id'=>$member_id,'createtime|bthan'=>$fromtime,'createtime|sthan'=>$totime,'status|noequal'=>'dead');//modify by hzk 05-26 排除废单 status = dead
       
           //根据当前的促销条件到订单中心去获取当前这个人已经购买的数量
            $this_member_all_orders = $db_order->getList('order_id,member_id', $filter, 0, -1, 'order_id ASC');
          

  
            $db_order_goods = app::get('b2c')->model('order_items');
            $gift_type = app::get('b2c')->_('product');
            //促发条件的 个数 $rule_protion['conditions']['conditions'][0]['value']
            
            $order_goods_nums = 0;//当前用户之前购买的数量
            foreach ($this_member_all_orders as $one_order) {
                $temp_filter = array('order_id'=>$one_order,'item_type|nequal'=>$gift_type,'goods_id'=>$rule_protion['conditions']['conditions'][0]['conditions'][0]['value']);
                $temp_goods = $db_order_goods->getList('goods_id,name,nums,order_id', $temp_filter, 0, -1, 'order_id ASC');

                if(!empty($temp_goods) && (int)$temp_goods[0]['nums'] >= $rule_protion['conditions']['conditions'][0]['value'])
                {
                    $order_goods_nums += (int)$temp_goods[0]['nums'];//总计订单中该商品的个数
                    
                }
            }
            return  $order_goods_nums;
    }
//////////////////////////////////
    /**
     * checkout 结果页面
     * @params int
     * @return null
     */
    public function checkout_result($isfastbuy=0){

      // echo "<pre>";
      // var_dump($this->pagedata['aCart']);
      // exit();
      
      // echo "456";
      // var_dump($isfastbuy);
      // exit;

      //@mo 2017年4月13日 17:57:15
      //默认fittocommit是可以提交没有超出限制个数
      $this->pagedata['fittocommit'] = app::get('b2c')->_('canbuy');

      //满足促销的促销规则
      $promotion_fullofgifts = $this->check_fullofgift($this->pagedata['aCart']);

       // echo "<pre>";
       // var_dump();
       // exit;

        if(!empty($promotion_fullofgifts))
        {
             $this->pagedata['fittocommit'] = $this->is_fit_to_order($promotion_fullofgifts,$this->pagedata['aCart']);
        }
        // echo '<pre>';
        // var_dump($this->pagedata['fittocommit']);
        // echo '==================y';
        //预售商品下单结算的判断
        if(!$isfastbuy)
        {
            $prepare=kernel::service('prepare_goods');
            if($prepare)
            {
                $pre=$prepare->get_product_buy($this->pagedata['aCart']['object']['goods']);
                foreach ($pre as $key => $value) {
                    $prep[] = $value['promotion_type'];
                }
                if (!empty($prep))
                {
                    $msg = app::get('b2c')->_('下单结算的商品里面不能含有预售商品！');
                    $url = $this->gen_url(array('app'=>'b2c','ctl'=>'wap_cart','act'=>'index','arg0'=>'true'));
                    if(in_array('prepare', $prep)){
                        $this->end('false',$msg);
                    }
                }
            }
        }
        $this->pagedata['checkout'] = 1;
        $this->pagedata['md5_cart_info'] = kernel::single("b2c_cart_objects")->md5_cart_objects($isfastbuy);
        //会员信息
        $arrMember = $this->get_current_member();
        $this->pagedata['member_id'] = $arrMember['member_id'];
        /** 判断请求的参数是否是group **/
        $arr_request_params = $this->_request->get_params();
        //是否是团购订单
        $arr_request_params[0] == 'group' ? $this->pagedata['is_group_orders'] = 'true' : $this->pagedata['is_group_orders'] = 'false';
        $this->pagedata['app_id'] = $app_id;
         //获取预售信息
        if(app::get('preparesell')->is_actived()){
            $preparesell_goods = app::get('preparesell')->model('preparesell_goods');
            $product_id=$this->pagedata['aCart']['object']['goods'][0]['params']['product_id'];
            $arrproducts = $preparesell_goods->getRow('promotion_type',array('product_id'=>$product_id));
        }

        // 如果会员已登录，查询会员的信息
        $obj_member_addrs = $this->app->model('member_addrs');
        $obj_dltype = $this->app->model('dlytype'); //配送方式model
        $member_point = 0; //会员积分
        $str_def_currency = $arrMember['member_cur'] ? $arrMember['member_cur'] : ""; //会员设置的默认货币

        /*获取收货地址 start*/
        $def_addr = kernel::single('b2c_member_addrs')->get_default_addr($arrMember['member_id']);
        $this->pagedata['def_addr'] = $def_addr;
        $member_addr_list = $obj_member_addrs->getList('*',array('member_id'=>$arrMember['member_id']));
        $this->pagedata['member_addr_list'] = $member_addr_list;
        //邮编是否开启
        $this->pagedata['site_checkout_zipcode_required_open'] = $this->app->getConf('site.checkout.zipcode.required.open');
        /* 是否开启配送时间的限制 */
        $this->pagedata['site_checkout_receivermore_open'] = $this->app->getConf('site.checkout.receivermore.open');
        /*收货地址 end*/

        if($def_addr){
            //是否有默认的当前的配送方式
            $area = explode(':',$def_addr['area']);
            $this->pagedata['dlytype_html'] = kernel::single('b2c_order_dlytype')->select_delivery_method($this,$area[2],$this->pagedata['aCart']);


            //add by lkb 如果后台设置默认配送方式就直接赋值
            // $oObj_data=$obj_dltype->getList('*',array('is_default'=>'1'),0,1);
            // if(count($oObj_data))
            // {
            //     $this->pagedata['shipping_method']["shipping_id"]=$oObj_data[0]['dt_id'];
            //     $this->pagedata['shipping_method']["shipping_name"]=$oObj_data[0]['dt_name'];
            //     $this->pagedata['shipping_method']["has_cod"]=$oObj_data[0]['has_cod'];
            //     $this->pagedata['shipping_method']["is_protect"]=$oObj_data[0]['protect'];
            // }
            
            // if(isset($_COOKIE['purchase']['shipping']) && $_COOKIE['purchase']['shipping'])
            // {
            //     $this->pagedata['shipping_method'] = (isset($_COOKIE['purchase']['shipping']) && $_COOKIE['purchase']['shipping']) ? unserialize($_COOKIE['purchase']['shipping']) : '';
            // }
            //add end


            // $this->pagedata['shipping_method'] = (isset($_COOKIE['purchase']['shipping']) && $_COOKIE['purchase']['shipping']) ? unserialize($_COOKIE['purchase']['shipping']) : '';
            //预售信息的判断，排除线下支付
            if($arrproducts['promotion_type']!='prepare')
            {
                $this->pagedata['has_cod'] = (isset($this->pagedata['shipping_method']['has_code']) && $this->pagedata['shipping_method']['has_cod']) ? $this->pagedata['shipping_method']['has_cod'] : 'false';
            }
            //预售信息的判断，排除货到付款
            if($arrproducts['promotion_type']=='prepare')
            {
               $this->pagedata['has_cod'] = 'false';
            }
        }

        $currency = app::get('ectools')->model('currency');
        if($this->pagedata['shipping_method']){
            // 是否有默认的支付方式
            $this->pagedata['arr_def_payment'] = (isset($_COOKIE['purchase']['payment']) && $_COOKIE['purchase']['payment']) ? unserialize($_COOKIE['purchase']['payment']) : '';
            /*支付方式列表*/
            $currency = app::get('ectools')->model('currency');
            $this->pagedata['currencys'] = $currency->getList('cur_id,cur_code,cur_name');
            if (!$str_def_currency){
                $arrDefCurrency = $currency->getDefault();
                $str_def_currency = $arrDefCurrency['cur_code'];
            }else{
                $arrDefCurrency = $currency->getcur($str_def_currency);
            }
            $aCur = $currency->getcur($str_def_currency);
            $this->pagedata['current_currency'] = $str_def_currency;
            $obj_payments = kernel::single('ectools_payment_select');
            //预售信息的判断，排除线下支付
            if($arrproducts['promotion_type']=='prepare')
            {
                $arrDefCurrency['no_offline']='true';
            }
            $this->pagedata['payment_html'] = $obj_payments->select_pay_method($this, $arrDefCurrency, $arrMember['member_id']);
            /*end*/

            $ret = $currency->getFormat();
            $ret =array(
                'decimals'=>$this->app->getConf('system.money.decimals'),
                'dec_point'=>$this->app->getConf('system.money.dec_point'),
                'thousands_sep'=>$this->app->getConf('system.money.thousands_sep'),
                'fonttend_decimal_type'=>$this->app->getConf('system.money.operation.carryset'),
                'fonttend_decimal_remain'=>$this->app->getConf('system.money.decimals'),
                'sign' => $ret['sign']
            );
            $this->pagedata['money_format'] = json_encode($ret);
        }

        //是否开启发票
        $trigger_tax = $this->app->getConf('site.trigger_tax');
        if($trigger_tax == 'true'){
            $personal_tax_ratio = $this->app->getConf('site.personal_tax_ratio'); //个人发票税率
            $company_tax_ratio = $this->app->getConf('site.company_tax_ratio'); //公司发票税率
            $tax_content = $this->app->getConf('site.tax_content'); //发票内容选项
            if($tax_content){
                $arr_tax_content = explode(',',$tax_content);
                foreach($arr_tax_content as $tax_content_value){
                    $select_tax_content[$tax_content_value] = $tax_content_value;
                }
            }
            $tax_setting = array(
                'trigger_tax' => $trigger_tax,
                'personal_tax_ratio' => $personal_tax_ratio,
                'company_tax_ratio' => $company_tax_ratio,
                'tax_content' =>$select_tax_content ? $select_tax_content : 0,
            );
            $this->pagedata['tax_setting'] = $tax_setting;
        }//end 发票

        /**
         * 取到优惠券的信息
         */
        $oCoupon = kernel::single('b2c_coupon_mem');
        $aData = $oCoupon->get_list_m($arrMember['member_id']);
        if( is_array($aData) ) {
            $curTime = time();
            foreach( $aData as $_key => $_val ) {
                // 验证优惠券是否开始使用、是否过期、是否使用、是否禁用，注销不符合条件的优惠券
                if ($curTime<$_val['time']['from_time'] || $curTime>=$_val['time']['to_time'] || $_val['memc_used_times'] || !$_val['coupons_info']['cpns_status']) {
                    unset($aData[$_key]);
                }
            }
        }
        $this->pagedata['coupon_lists'] = $aData;
        /*end*/

        // echo "<pre>";
        // var_dump($this->pagedata['aCart']['object']['goods']);
        // exit;

        $goods = $this->pagedata['aCart']['object']['goods'];      

        // 商品数量

        //获取当前会员id
        $members=array("member_id"=>kernel::single('b2c_user_object')->get_member_session());
        $member_id = $members['member_id'];

        foreach ($goods as $key => $value) {
           $gid[] = $value["params"];
        }

       foreach ($goods as $key => $value) {

         $obj_ident = $value['obj_ident'];

         //首先获取该用户的购物车里的该商品数量
         $sql = "select obj_ident,quantity from sdb_b2c_cart_objects where obj_ident = '$obj_ident' and member_id = '$member_id'";
         $this->db = kernel::database();
         $quantity0[$key] = $this->db->select($sql);

        } 

        $newquantity = array();
        foreach ($quantity0 as $key => $value) {
          $newquantity[$key] = $value[0];
        }

        foreach ($goods as $key => $value) {
            
            if ($isfastbuy == true) {
              // 若是立即订购，那么从商品详情页面获取购买数量
              $aa = $this->pagedata['aCart'];
              $goods[$key]['quantity'] = $aa['object']['goods'][0]['quantity'];
              // var_dump($goods[$key]['quantity']);
              // exit();
            }else{
              //若是加入购物车再结算，那么从购物车获取购买数量
              $goods[$key]['quantity'] = $newquantity[$key]['quantity'];
            }
          
        }

        // echo "<pre>";
        // var_dump($goods);
        // exit(); 

        $this->pagedata['aCart']['object']['goods'] = $goods;

        //计算商品总金额

        $gg = $this->pagedata['aCart'];

        // echo "<pre>";
        // var_dump($gg);
        // exit();

        // echo "<pre>";
        // var_dump($gg['object']['goods'][0]['obj_items']['products']);
        // exit();

        foreach ($gg['object']['goods'] as $key => $value) {
          $mlv_price = $value['obj_items']["products"][0]["price"]["mlv_price"];
          $quantity = $value['quantity'];
          $tot[] = $mlv_price*$quantity;
        }

        // echo "<pre>";
        // var_dump($quantity);
        // exit();

        $totmoney = '';
        //判断购物车是否只有一个商品，进行计算商品总金额
        foreach ($tot as $key => $value) {

          if (count($tot)>1) {
          $totmoney +=  $value;
          }else{
            $totmoney = $value;
          }

        }

        // echo "<pre>";
        // var_dump($totmoney);
        // exit();

        // 商品总金额
        $total_item = $totmoney;

        // var_dump($total_item);
        // exit();

        // $total_item = $this->objMath->number_minus(array($this->pagedata['aCart']["subtotal"], $this->pagedata['aCart']['discount_amount_prefilter']));

        // 取到商店积分规则
        $policy_method = $this->app->getConf("site.get_policy.method");
        switch ($policy_method)
        {
            case '1':
                $subtotal_consume_score = 0;
                $subtotal_gain_score = 0;
                $totalScore = 0;
                break;
            case '2':
                $subtotal_consume_score = round($this->pagedata['aCart']['subtotal_consume_score']);
                $policy_rate = $this->app->getConf('site.get_rate.method');

                //订单可得积分
                // $subtotal_gain_score = round($this->objMath->number_plus(array(0, $this->pagedata['aCart']['subtotal_gain_score'])));
                $subtotal_gain_score = round($total_item);

                $totalScore = round($this->objMath->number_minus(array($subtotal_gain_score, $subtotal_consume_score)));
                break;
            case '3':
                $subtotal_consume_score = round($this->pagedata['aCart']['subtotal_consume_score']);
                $subtotal_gain_score = round($this->pagedata['aCart']['subtotal_gain_score']);
                $totalScore = round($this->objMath->number_minus(array($subtotal_gain_score, $subtotal_consume_score)));
                break;
            default:
                $subtotal_consume_score = 0;
                $subtotal_gain_score = 0;
                $totalScore = 0;
                break;
        }

        //订单总金额
        // $total_amount = $this->objMath->number_minus(array($this->pagedata['aCart']["subtotal"], $this->pagedata['aCart']['discount_amount']));

        $total_amount = $totmoney;

        if ($total_amount < 0) $total_amount = 0;

        // 是否可以用积分抵扣
        $obj_point_dis = kernel::service('b2c_cart_point_discount');
        if ($obj_point_dis){
            $obj_point_dis->set_order_total($total_amount);
            $this->pagedata['point_dis_html'] = $obj_point_dis->get_html($arrMember['member_id'], 'wap/cart/point_dis.html');
            $this->pagedata['point_dis_js'] = $obj_point_dis->get_javascript($arrMember['member_id']);
        }

        // 得到cart total支付的信息
        $this->pagedata['order_detail'] = array(
            'cost_item' => $total_item,
            'total_amount' => $total_amount,
            'currency' => $this->app->getConf('site.currency.defalt_currency'),
            'pmt_order' => $this->pagedata['aCart']['discount_amount_order'],
            'pmt_amount' => $this->pagedata['aCart']['discount_amount'],
            'totalConsumeScore' => $subtotal_consume_score,
            'totalGainScore' => $subtotal_gain_score,
            'totalScore' => $totalScore,
            'cur_code' => $strDefCurrency,
            'cur_display' => $strDefCurrency,
            'cur_rate' => $aCur['cur_rate'],
            'final_amount' => $currency->changer($total_amount, $this->app->getConf("site.currency.defalt_currency"), true),
        );

        // echo "<pre>";
        // var_dump($this->pagedata['order_detail']);
        // exit;

        //会员积分
       $this->pagedata['order_detail']['totalScore'] = $member_point;
        $odr_decimals = $this->app->getConf('system.money.decimals');
        $total_amount = $this->objMath->get($this->pagedata['order_detail']['total_amount'], $odr_decimals);
        $this->pagedata['order_detail']['discount'] = $this->objMath->number_minus(array($this->pagedata['order_detail']['total_amount'], $total_amount));
        $this->pagedata['order_detail']['total_amount'] = $total_amount;
        $this->pagedata['order_detail']['current_currency'] = $strDefCurrency;


        // 获得商品的赠品信息
        $arrM_info = array();
        foreach ($this->pagedata['aCart']['object']['goods'] as $arrGoodsInfo){
            if (isset($arrGoodsInfo['gifts']) && $arrGoodsInfo['gifts']){
                $this->pagedata['order_detail']['gift_p'][] = array(
                    'storage' => $arrGoodsInfo['gifts']['storage'],
                    'name' => $arrGoodsInfo['gifts']['name'],
                    'nums' => $arrGoodsInfo['gifts']['nums'],
                );
            }

            // 得到商品购物信息的必填项目
            $goods_id = $arrGoodsInfo['obj_items']['products'][0]['goods_id'];
            $product_id = $arrGoodsInfo['obj_items']['products'][0]['product_id'];
            // 得到商品goods表的信息
            $objGoods = $this->app->model('goods');
            $arrGoods = $objGoods->dump($goods_id, 'type_id');
            if (isset($arrGoods) && $arrGoods && $arrGoods['type']['type_id']){
                $objGoods_type = $this->app->model('goods_type');
                $arrGoods_type = $objGoods_type->dump($arrGoods['type']['type_id'], '*');

                if ($_COOKIE['checkout_b2c_goods_buy_info']){
                    $goods_need_info = json_decode($_COOKIE['checkout_b2c_goods_buy_info'], 1);

                }
                if ($arrGoods_type['minfo']){
                    if ($arrGoodsInfo['obj_items']['products'][0]['spec_info']){
                        $arrM_info[$product_id]['name'] = $arrGoodsInfo['obj_items']['products'][0]['name'] . '(' . $arrGoodsInfo['obj_items']['products'][0]['spec_info'] . ')';
                    }else{
                        $arrM_info[$product_id]['name'] = $arrGoodsInfo['obj_items']['products'][0]['name'];
                    }
                    $arrM_info[$product_id]['nums'] = $this->objMath->number_multiple(array($arrGoodsInfo['obj_items']['products'][0]['quantity'],$arrGoodsInfo['quantity']));

                    foreach ($arrGoods_type['minfo'] as $key=>$arr_minfo){
                        if (isset($goods_need_info[$product_id][$key]) && $arr_minfo['label'] == $goods_need_info[$product_id][$key]['name']){
                            $arr_minfo['value'] = $goods_need_info[$product_id][$key]['val'][0];
                        }else{
                            $no_value = true;
                        }
                        $arrM_info[$product_id]['minfo'][] = $arr_minfo;
                    }
                }
            }
        }

        if($no_value){
            $this->pagedata['has_goods_minfo'] = false;
        }else{
            $this->pagedata['has_goods_minfo'] = true;
        }
        $this->pagedata['minfo'] = $arrM_info;
        $this->pagedata['base_url'] = kernel::base_url().'/';
        // checkout result 页面添加项目埋点
        foreach( kernel::servicelist('b2c.checkout_add_item') as $services ) {
            if ( is_object($services) ) {
                if ( method_exists($services, 'addItem') ) {
                    $services->addItem($this);
                }
            }
        }
        //获取预售信息
       /* $objproducts = $this->app->model('products');
        $product_id=$this->pagedata['aCart']['object']['goods'][0]['params']['product_id'];
        $arrproducts = $objproducts->dump($product_id, 'promotion_type');*/
        $prepare=kernel::service('prepare_prepare');
        if($prepare)
        {
            $pre=$prepare->getSpecialProduct($product_id);
            $this->pagedata['prepare']=$pre;
            $this->pagedata['promotion_type']=$pre['promotion_type'];
        }
        $this->pagedata['promotion_type']=$arrproducts['promotion_type'];
            //echo '<pre>';print_r($prepare);exit();


        //add by lkb 去掉失效赠品 lkb 2017-6-2
    if(count($this->pagedata['aCart']['object']['gift']['order']))
    {
    for($i=0;$i<count($this->pagedata['aCart']['object']['gift']['order']);$i++)
    {
        if($this->pagedata['aCart']['object']['gift']['order'][$i]['quantity']==0)
        {
            unset($this->pagedata['aCart']['object']['gift']['order'][$i]);
        }
    }
    }
    //add end
    
        $this->page('wap/cart/checkout/index.html',false,$app_id);
    }

    //送货地址编辑
    function shipping_edit($isfastbuy=false){
        $this->set_header();

        $this->pagedata['is_fastbuy'] = $isfastbuy;
        //邮编是否开启
        $this->pagedata['site_checkout_zipcode_required_open'] = $this->app->getConf('site.checkout.zipcode.required.open');
        $arrMember = $this->get_current_member();
        if( $_POST['address'] && $arrMember['member_id']){
            $address = json_decode($_POST['address'],true);
            $addr = app::get('b2c')->model('member_addrs')->getList('*',array('addr_id'=>$address['addr_id'],'member_id'=>$arrMember['member_id']));
            $this->pagedata['edit_addr'] = $addr[0];
        }
        $this->pagedata['is_shipping_edit'] = true;
        $this->pagedata['site_checkout_receivermore_open'] = $this->app->getConf('site.checkout.receivermore.open');
        //邮编是否开启
        $this->pagedata['site_checkout_zipcode_required_open'] = $this->app->getConf('site.checkout.zipcode.required.open');
        /* 是否开启配送时间的限制 */
        $this->pagedata['site_checkout_receivermore_open'] = $this->app->getConf('site.checkout.receivermore.open');

        $this->page('wap/cart/checkout/shipping_edit.html');

    }

    //保存送货地址
    function shipping_save($isfastbuy=false){
        $this->set_header();
        $arrMember = $this->get_current_member();
        $next_url = $this->gen_url(array('app'=>'b2c','ctl'=>'wap_cart','act'=>'checkout','arg0'=>$isfastbuy));
        if($_POST['address']){
            $address = json_decode($_POST['address'],true);
            unset($_POST['address']);
            $_POST['addr_id'] = $address['addr_id'];
        }
        if(!$_POST['addr_id']){
            $this->pagedata['shipping_add'] = 'true';
        }
        if($this->app->getConf('site.checkout.zipcode.required.open') == 'true' && empty($_POST['zip']) ) {
            $this->splash('error',null,app::get('b2c')->_('邮编为必填项'),'','',true);
        }
        $save_data = kernel::single('b2c_member_addrs')->purchase_save_addr($_POST,$arrMember['member_id'],$msg);
        if($save_data){
            $this->pagedata['save_addr'] = $save_data;
            $this->splash('success',$next_url,app::get('b2c')->_('添加收货地址成功'),'','',true);
        }else{
            echo json_encode( array('error' => $msg));exit;
        }
        /* 是否开启配送时间的限制 */
        //$this->pagedata['site_checkout_receivermore_open'] = $this->app->getConf('site.checkout.receivermore.open');
        //echo $this->fetch('wap/cart/checkout/shipping_save.html');
        header("Location: ".$next_url);
    }

    //删除送货地址
    function shipping_delete(){
        $arrMember = $this->get_current_member();
        if($arrMember['member_id']  && $_POST['address'] ){
            $address = json_decode($_POST['address'],true);
            $flag =  app::get('b2c')->model('member_addrs')->delete(array('addr_id'=>$address['addr_id'],'member_id'=>$arrMember['member_id']));
            if( $flag )
                echo  json_encode(array('success'=>'删除成功'));
            else
                echo  json_encode(array('error'=>'删除失败'));
        }else{
            echo json_encode(array('error'=>'会员未登录或参数错误'));
        }
        exit;
    }

    //确认送货地址
    function shipping_confirm(){
        $this->set_header();
        $arrMember = $this->get_current_member();
        $member_id = $arrMember['member_id'];
        $obj_addr = kernel::single('b2c_member_addrs');
        //新增地址
        if(!$_POST['address']){
            $save_data = $obj_addr->purchase_save_addr($_POST,$member_id,$msg);
            $addr_id = $save_data['addr_id'];
            $this->pagedata['def_addr'] = $save_data;
        }else{
            $address = json_decode($_POST['address'],true);
            if($address['addr_id']){
                $def_addr = app::get('b2c')->model('member_addrs')->getList('*',array('addr_id'=>$address['addr_id']));
                if($this->app->getConf('site.checkout.zipcode.required.open') == 'true' && empty($def_addr[0]['zip']) ) {
        $this->splash('failed',null,app::get('b2c')->_('邮编为必填项'),'','',true);
                }
                if($def_addr){
                    $this->pagedata['def_addr'] = $def_addr['0'];
                }else{
                    echo json_encode(array('error'=>app::get('b2c')->_('收货地址ID错误')));exit;
                }
            }else{
               echo json_encode(array('error'=>app::get('b2c')->_('收货地址ID错误')));
            }
            $addr_id = $address['addr_id'];
        }
        $this->pagedata['site_checkout_receivermore_open'] = $this->app->getConf('site.checkout.receivermore.open');
        $seKey = md5($this->obj_session->sess_id().$member_id);
        setcookie('purchase[addr][usable]', $seKey, 0, kernel::base_url() . '/');
        setcookie('purchase[addr][addr_id]', $addr_id, 0, kernel::base_url() . '/');
        setcookie("purchase[shipping]", "", time() - 3600, kernel::base_url().'/');
        setcookie("purchase[payment]", "", time() - 3600, kernel::base_url().'/');
        $this->app->model('members')->update(array('addon'=>$this->pagedata['def_addr']), array('member_id'=>$member_id));
        echo $this->fetch('wap/cart/checkout/shipping_confirm.html');
    }


    //配送方式根据送货地址联动
    public function delivery_change(){
        $this->set_header();
        $this->_common(false,$_POST['isfastbuy']);
        $area_id = $_POST['area'];
        $shipping_method = $_POST['shipping_method'];
        $obj_delivery = new b2c_order_dlytype();
        $sdf = array();
        $sdf = $this->pagedata['aCart'];
        if (isset($_POST['payment']) && $_POST['payment'])
            $sdf['pay_app_id'] = $_POST['payment'];
        $this->pagedata['app_id'] = $app_id;
        echo $obj_delivery->select_delivery_method($this,$area_id,$sdf,$shipping_method,'wap/cart/checkout/delivery_list.html');exit;
    }

    //确认配送方式
    public function delivery_confirm(){
        $this->set_header();
        if (!isset($_POST['shipping']) || !$_POST['shipping']){
            echo json_encode(array('error'=>app::get('b2c')->_('配送方式的id不能为空！')));exit;
        }

        $shipping = json_decode($_POST['shipping'],true);
        $arr_shipping = array(
            'shipping_id'=>$shipping['id'],
            'shipping_name'=>$shipping['dt_name'],
            'money'=>$shipping['money'],
            'has_cod'=>$shipping['has_cod'],
            'is_protect'=>$_POST['is_protect'],
        );
        setcookie('purchase[shipping]', serialize($arr_shipping), 0, kernel::base_url() . '/');
        setcookie("purchase[payment]", "", time() - 3600, kernel::base_url().'/');
        $this->pagedata['shipping_method'] = $arr_shipping;
        echo $this->fetch('wap/cart/checkout/delivery_confirm.html');
    }

    //支付方式根据配送方式联动
    public function payment_change($no_offline){
        $this->set_header();
        $obj_payment_select = new ectools_payment_select();
        if($_POST['payment']['currency']){
            $sdf['cur'] = $_POST['payment']['currency'];
        }

        if($_POST['shipping']){
            $shipping = json_decode($_POST['shipping'],true);
            $this->pagedata['has_cod'] = $shipping['has_cod'];
        }
         //预售商品的判断
        if($no_offline=='prepare')
        {
            $sdf['no_offline']='true';
            $this->pagedata['has_cod'] = 'false';
        }
        $currency = app::get('ectools')->model('currency');
        $this->pagedata['currencys'] = $currency->getList('cur_id,cur_code,cur_name');
        $currency = $currency->getRow('cur_id,cur_code,cur_name',array('cur_default'=>'true'));
        $def_currency = $currency['cur_code'] ? $currency['cur_code'] : app::get('b2c')->getConf('site.currency.defalt_currency');
        $this->pagedata['current_currency'] = $sdf['cur'] ? $sdf['cur'] : $def_currency;
        $this->pagedata['app_id'] = $app_id;
        echo $obj_payment_select->select_pay_method($this, $sdf, false,false,array('iscommon','iswap'),'wap/cart/checkout/select_currency.html');exit;
    }

    // 确认支付方式
    public function payment_confirm(){
        $this->set_header();
        if (!isset($_POST['payment']['pay_app_id']) || !$_POST['payment']['pay_app_id']){
            $msg =  app::get('b2c')->_('请选择一种支付方式');
            echo json_encode(array('error'=>$msg));exit;
        }

        $payment_info = json_decode($_POST['payment']['pay_app_id'],true);
        $arr_payment = array(
            'pay_app_id'=>$payment_info['pay_app_id'],
            'app_display_name'=>$payment_info['payment_name'],
        );
        setcookie('purchase[payment]', serialize($arr_payment), 0, kernel::base_url() . '/');
        $this->pagedata['arr_def_payment'] = $arr_payment;
        echo $this->fetch('wap/cart/checkout/payment_confirm.html');
    }


    public function total(){
        $this->_common(false,$_POST['isfastbuy']);
        $obj_total = new b2c_order_total();
        $sdf_order = $_POST;
        if($_POST){
            $payment = json_decode($_POST['payment']['pay_app_id'],true);
            $shipping = json_decode($_POST['shipping'],true);
            $address = json_decode($_POST['address'],true);
            $address_area = explode(':',$address['area']);
        }
        $sdf_order['cur'] = $_POST['payment']['currency'];
        $sdf_order['shipping_id'] = $shipping['id'];
        $sdf_order['is_protect'] = $_POST['is_protect'];
        $sdf_order['is_tax'] = $_POST['payment']['is_tax'];
        $sdf_order['tax_type'] = $_POST['payment']['tax_type'];
        $sdf_order['payment'] = $payment['pay_app_id'];
        $arrMember = $this->get_current_member();
        $sdf_order['member_id'] = $arrMember['member_id'];
        $sdf_order['area_id'] = $address_area[2]?$address_area[2]:$address['area'];
        $sdf_order['dis_point'] = floor($_POST['point']['score']);
        $arr_cart_object = $this->pagedata['aCart'];
        //预售商品前台显示
        $product_id=$this->pagedata['aCart']['object']['goods'][0]['params']['product_id'];
        $prepare=kernel::service('prepare_prepare');
        if($prepare)
        {
            $pre=$prepare->getSpecialProduct($product_id);
            $arr_cart_object['promotion_type']=$pre['promotion_type'];
            $arr_cart_object['prepare']=$pre;
        }
        $this->set_header();
        echo $obj_total->order_total_method($this,$arr_cart_object,$sdf_order,"false","wap/cart/checkout/checkout_total.html");exit;
    }
    /* 订单确认页end*/

    //widgets cart
    public function view(){
        $oCart = $this->app->model("cart_objects");
        $arr = array();
        $aData = $oCart->setCartNum( $arr );
        $this->pagedata['trading'] = $aData['trading'];
        $this->pagedata['cartCount'] = $aData['CART_COUNT'];
        $this->pagedata['cartNumber'] = $aData['CART_NUMBER'];
        $this->_common();

        // 购物车数据项的render 迷你购物车
        $this->pagedata['item_section'] = $this->mCart->get_item_render_view();

        // 购物车数据项的render
        $this->pagedata['item_goods_section'] = $this->mCart->get_item_goods_render_view();

        $tpl = 'wap/cart/view.html';
        $this->page($tpl, true);
    }

    public function loginBuy($isfastbuy=0)
    {
        if( $this->check_login() ) {
            $this->begin( $this->gen_url( array('app'=>'b2c','act'=>'index','ctl'=>'wap_cart') ) );
            $this->end( true,'您已经是登录状态！');
        }

        if($isfastbuy){
          $_SESSION['mobile_next_page'] = $this->gen_url(array('app'=>'b2c','ctl'=>'wap_cart','act'=>'checkout','arg0'=>'true'));
        }else{
          $_SESSION['mobile_next_page'] = $this->gen_url(array('app'=>'b2c','ctl'=>'wap_cart','act'=>'checkout'));
        }

        $url = $this->gen_url(array('app'=>'b2c','ctl'=>'wap_passport','act'=>'login','arg0'=>$_GET['mini_passport']));
        $this->redirect($url);
    }

    ////////////////////////////// 以下私有函数/////////////////////////////

    private function _cart_main($msg='',$json_type='all') {
        $aParams = $this->_request->get_params(true);

        // add by hyz 2017.11.15 19:50

        //当前商品id 
        $goods_ident = $aParams["goods_ident"];
        //是否有优惠
        $status = $aParams['status'];
        //促销价格
        $total_amount = $aParams['total_amount'];
        //促销商品数量
        $fixed_nums = $aParams['fixed_nums'];
        //购买商品数量
        $quantity = $aParams["modify_quantity"][$goods_ident]["quantity"];
        //渠道商等级价格
        $member_lv_price = $aParams['member_lv_price'];
        //订货价
        $mlv_price = $aParams['mlv_price'];
        //打折优惠总金额
        $discount_amount_prefilter = $aParams['discount_amount_prefilter'];
        //折扣后的商品价格
        $dis_price = $aParams['dis_price'];

        // echo "<pre>";
        // var_dump($status);
        // var_dump($total_amount);
        // var_dump($fixed_nums);
        // var_dump($quantity);
        // var_dump($member_lv_price);
        // var_dump($mlv_price);
        // var_dump($discount_amount_prefilter);
        // var_dump($dis_price);

        if ($status==1) {
            // 有优惠
            if ($total_amount) {
                // 价格打折方式
                if ($fixed_nums) {
                    // 如果存在限定促销的商品数量，限量促销
                    if ($quantity>$fixed_nums) {
                        // 购买商品数量大于商品促销数量
                        if ($member_lv_price) {
                            // 存在渠道商等级价格
                            $tol = ($total_amount*$fixed_nums)+($quantity-$fixed_nums)*$member_lv_price;

                        }else{
                            // 不存在渠道等级价格
                            $tol = ($total_amount*$fixed_nums)+($quantity-$fixed_nums)*$mlv_price;
                        }
                    }else{
                        //购买商品数量小于商品促销数量
                        $tol = $total_amount*$quantity;
                    }
                }else{
                    // 如果不存在限定促销的商品数量，不限量促销
                    // if ($member_lv_price) {
                        // 存在渠道商等级价格
                        // $tol = ($mlv_price*$quantity)-($discount_amount_prefilter+(($mlv_price-$member_lv_price)*$quantity));

                        $tol = $total_amount*$quantity;
                    // }else{
                        // 不存在渠道等级价格
                        // $tol = ($member_lv_price*$quantity)-$discount_amount_prefilter;
                        // $tol = $total_amount*$quantity;
                    // }
                }
            }else{
                // 折扣打折方式
                // if ($member_lv_price) {
                    // 存在渠道商等级价格
                    // $tol = ($mlv_price*$quantity)-($discount_amount_prefilter+(($mlv_price-$member_lv_price)*$quantity));

                    $tol = $dis_price*$quantity;
                // }else{
                    // 不存在渠道等级价格
                    // $tol = ($member_lv_price*$quantity)-$discount_amount_prefilter;
                // }
            } 
        }else{
            //没有优惠
            if ($member_lv_price) {
                // 存在渠道商等级价格
                $tol = $member_lv_price*$quantity;
            }else{
                // 不存在渠道等级价格
                $tol = $mlv_price*$quantity;
            }
        }
        // end hyz 2017.11.15 19:50

        if (!$msg) $msg = app::get('b2c')->_('购物车修改成功！');
        $obj_currency = app::get('ectools')->model('currency');
        $this->pagedata['ajax_html'] = $this->ajax_html;

        $this->_common(1,$aParams['is_fastbuy']);

        if( !$this->pagedata['is_empty'] ) {
            foreach($this->pagedata['aCart']['object']['gift']['order']  as $gift_key=>$gift_obj){
                $order_gift[$gift_key]['url'] = $gift_obj['url'];
                $order_gift[$gift_key]['thumbnail'] = $gift_obj['thumbnail'];
                $order_gift[$gift_key]['name'] = $gift_obj['name'];
                $order_gift[$gift_key]['spec_info'] = $gift_obj['spec_info'];
                $order_gift[$gift_key]['quantity'] = $gift_obj['quantity'];
                $order_gift[$gift_key]['price'] =$obj_currency->changer_odr($gift_obj['price']['price'],$_COOKIE["S"]["CUR"],false,false,$system_money_decimals,$system_money_operation_carryset);
            }

            $this->pagedata['aCart']['promotion_subtotal'] = $this->objMath->number_minus(array($this->pagedata['aCart']['subtotal'], $this->pagedata['aCart']['subtotal_discount']));
            $system_money_decimals = app::get('b2c')->getConf('system.money.decimals');
            $system_money_operation_carryset = app::get('b2c')->getConf('system.money.operation.carryset');

            //小计传值给ajax
            // $this->pagedata['edit_ajax_data']['mlv_price'] = $obj_currency->changer_odr(sprintf("%.2f",$tol));

            $this->pagedata['edit_ajax_data']['mlv_price'] = "￥".sprintf("%.2f",$tol);

            switch ($json_type)
            {
                case 'mini':
                    $arr_json_data = array(
                        'sub_total'=>array(
                            'promotion_subtotal'=>$obj_currency->changer_odr($aCart['promotion_subtotal'],$_COOKIE["S"]["CUR"],false,false,$system_money_decimals,$system_money_operation_carryset),
                        ),
                        'is_checkout'=>false,
                        'number'=>array(
                                'cart_number'=>$this->pagedata['aCart']['_cookie']['CART_NUMBER'],
                                'cart_count'=>$this->pagedata['aCart']['_cookie']['CART_COUNT'],
                        ),
                        'error_msg'=>$this->pagedata['error_msg'],
                    );
                    $view = 'wap/cart/mini_index.html';
                break;
                case 'middle':
                    $arr_json_data = array(
                        'sub_total'=>array(
                            'subtotal_prefilter_after'=>$obj_currency->changer_odr($aCart['subtotal_prefilter_after'],$_COOKIE["S"]["CUR"],false,false,$system_money_decimals,$system_money_operation_carryset),
                            'promotion_subtotal'=>$obj_currency->changer_odr($aCart['promotion_subtotal'],$_COOKIE["S"]["CUR"],false,false,$system_money_decimals,$system_money_operation_carryset),
                        ),
                        'is_checkout'=>false,
                        'number'=>array(
                                'cart_number'=>$this->pagedata['aCart']['_cookie']['CART_NUMBER'],
                                'cart_count'=>$this->pagedata['aCart']['_cookie']['CART_COUNT'],
                        ),
                        'error_msg'=>$this->pagedata['error_msg'],
                    );
                    if ($this->pagedata['aCart']['discount_amount_order'] > 0)
                        $arr_json_data['sub_total']['discount_amount_order'] = $obj_currency->changer_odr($this->pagedata['aCart']['discount_amount_order'],$_COOKIE["S"]["CUR"],false,false,$system_money_decimals,$system_money_operation_carryset);
                    else
                        $arr_json_data['sub_total']['discount_amount_order'] = 0;
                    $view = 'wap/cart/middle_index.html';
                break;
                case 'coupon':
                    if(!empty($this->pagedata['aCart']['object']['coupon'])){
                        $return_coupon_data = array();
                        foreach($this->pagedata['aCart']['object']['coupon'] as $key=>$coupon_data){
                            if($coupon_data['used'] == 'true'){
                                $return_coupon_data[$key]['coupon'] = $coupon_data['coupon'];
                                $return_coupon_data[$key]['cpns_id'] = $coupon_data['cpns_id'];
                                $return_coupon_data[$key]['name'] = $coupon_data['name'];
                                $return_coupon_data[$key]['obj_ident'] = $coupon_data['obj_ident'];
                            }
                        }
                    }
                    $arr_json_data = array(
                        'success'=> $msg,
                        'data'=>$return_coupon_data,
                    );
                break;
                case 'all':
                default:
                    $arr_json_data = array(
                        'success'=> $msg,
                        'sub_total'=>array(
                            'subtotal_prefilter_after'=>$obj_currency->changer_odr($this->pagedata['aCart']['subtotal_prefilter_after'],$_COOKIE["S"]["CUR"],false,false,$system_money_decimals,$system_money_operation_carryset),
                            'promotion_subtotal'=>$obj_currency->changer_odr($this->pagedata['aCart']['promotion_subtotal'],$_COOKIE["S"]["CUR"],false,false,$system_money_decimals,$system_money_operation_carryset),
                            'subtotal_gain_score' => $this->pagedata['aCart']['subtotal_gain_score'],
                        ),
                        'unuse_rule'=>$this->pagedata['unuse_rule'],
                        'is_checkout'=>false,
                        'edit_ajax_data'=>$this->pagedata['edit_ajax_data'],
                        'promotion'=>$this->pagedata['aCart']['promotion'],
                        'order_gift'=>$order_gift,
                        'error_msg'=>$this->pagedata['error_msg'],
                        'number'=>array(
                            'cart_number'=>$this->pagedata['aCart']['_cookie']['CART_NUMBER'],
                            'cart_count'=>$this->pagedata['aCart']['_cookie']['CART_COUNT'],
                        ),
                    );
                    if ($this->pagedata['aCart']['discount_amount_order'] > 0)
                        $arr_json_data['sub_total']['discount_amount_order'] = $obj_currency->changer_odr($this->pagedata['aCart']['discount_amount_order'],$_COOKIE["S"]["CUR"],false,false,$system_money_decimals,$system_money_operation_carryset);
                    else
                        $arr_json_data['sub_total']['discount_amount_order'] = 0;
                    $view = 'wap/cart/index.html';
                break;
            }
        }else{
            $arr_json_data = array(
                'is_empty' => 'true',
                'number'=>array(
                    'cart_number'=>$this->pagedata['aCart']['_cookie']['CART_NUMBER'],
                    'cart_count'=>$this->pagedata['aCart']['_cookie']['CART_COUNT'],
                ),
            );
       }

        $md5_cart_info = kernel::single('b2c_cart_objects')->md5_cart_objects();
        $arr_json_data['md5_cart_info'] = $md5_cart_info;
        $this->pagedata = $arr_json_data;
        $this->page($view);
    }

    public function _common($flag=0,$is_fastbuy=false) {
        // 购物车数据信息
        $aData = $this->_request->get_params(true);
        if($is_fastbuy){
            $aData['is_fastbuy'] = $is_fastbuy;
        }
        $aData['apply_platform'] = '2';
        $aCart = $this->mCart->get_objects($aData);

        //@zeng 2017.4.18 获取当前用户审核状态、会员等级  
        $member_id = kernel::single('b2c_user_object')->get_member_id();
        $userObjects = kernel::single('b2c_user_object');
        $member_lv_id=$userObjects->get_member_lv($member_id);
        $member_state=$userObjects->get_member_state($member_id);
        

        foreach ($aCart['object']['goods'] as $key => $value) {
            $aCart['object']['goods'][$key]['obj_items']['products'][0]['price']['status']=$member_state;
            $aCart['object']['goods'][$key]['obj_items']['products'][0]['price']['member_lv_id']=$member_lv_id;
             $aCart['object']['goods'][$key]['obj_items']['products'][0]['price']['goods_tips']=app::get('b2c')->model('tips')->getGoodsTips($aCart['object']['goods'][$key]['obj_items']['products'][0]['goods_id']);//发货提示
         //判断是否存在配件 存在则修改销售 by.wpn 5/23
        if($aCart['object']['goods'][$key]['adjunct']){   
     //判断会员是否设定会员等级价格 无则设定为出厂价 by.wpn 5-12 
      $members=array("member_id"=>kernel::single('b2c_user_object')->get_member_session());  
        if($members["member_id"]){ 
           foreach($aCart['object']['goods'][$key]['adjunct'] as $k => $values){


            $member_goods_lv_price=app::get('b2c')->model('goods_lv_price')->getList('product_id,price',array('product_id'=>$aCart['object']['goods'][$key]['adjunct'][0]["product_id"],'level_id'=>$member_lv_id));


            //modified by lkb 配件获取会员价，否则取出厂价
            if($member_lv_id){
                 $member_goods_lv_price=app::get('b2c')->model('goods_lv_price')->getList('product_id,price',array('product_id'=>$aCart['object']['goods'][$key]['adjunct'][0]["product_id"],'level_id'=>$member_lv_id));
                 
                        if($member_goods_lv_price[0]['price']){
                           $aCart['object']['goods'][$key]['adjunct'][$k]['json_price']['price']=$member_goods_lv_price[0]['price'];
                        }
                        else{
                            //显示出厂价
                           $aCart['object']['goods'][$key]['adjunct'][$k]['json_price']['price']=$aCart['object']['goods'][$key]['adjunct'][$k]["price"]['mlv_price'];
                        }
                      }
            // $member_goods_lv_price=app::get('b2c')->model('goods_lv_price')->getList('product_id,price',array('product_id'=>$aCart['object']['goods'][$key]['adjunct']['product_id'],'level_id'=>$member_lv_id));
            // if(!$member_goods_lv_price[0]['price']){
            //        if( $aCart['object']['goods'][$k]['adjunct'][$k]['json_price']){
                      
            //     $aCart['object']['goods'][$key]['adjunct'][$k]['json_price']['price']=$aCart['object']['goods'][$key]['adjunct'][$k]['price']['mlv_price'];
            //        }
            //          }
            //modified end

                      }
        }}
        }
        ////////////////////////////////////////////////////////////////

        $this->_item_to_disabled( $aCart,$flag ); //处理购物扯删除项
        $this->pagedata['aCart'] = $aCart;

        if( $this->show_gotocart_button ) $this->pagedata['show_gotocart_button'] = 'true';

        if( $this->ajax_update === true ) {
            foreach(kernel::servicelist('b2c_cart_object_apps') as $object) {
                if( !is_object($object) ) continue;

                //应该判断是否实现了接口
                if( !method_exists( $object,'get_update_num' ) ) continue;
                if( !method_exists( $object,'get_type' ) ) continue;

                $this->pagedata['edit_ajax_data'] = $object->get_update_num( $aCart['object'][$object->get_type()],$this->update_obj_ident );
                if( $this->pagedata['edit_ajax_data'] ) {
                    //$this->pagedata['edit_ajax_data'] = json_encode( $this->pagedata['edit_ajax_data'] );
                    if( $object->get_type()=='goods' ) {
                        $this->pagedata['update_cart_type_godos'] = true;
                        if( !method_exists( $object,'get_error_html' ) ) continue;
                        $this->pagedata['error_msg'] = $object->get_error_html( $aCart['object']['goods'],$this->update_obj_ident );
                    }
                    break;
                }
            }
        }


        // 购物车是否为空
        $this->pagedata['is_empty'] = $this->mCart->is_empty($aCart);
        //ajax_html 删除单个商品是触发
        if($this->ajax_html && $this->mCart->is_empty($aCart)) {
            $arr_json_data = array(
                'is_empty' => 'true',
                'number'=>array(
                    'cart_number'=>$this->pagedata['aCart']['_cookie']['CART_NUMBER'],
                    'cart_count'=>$this->pagedata['aCart']['_cookie']['CART_COUNT'],
                ),
            );
            $this->pagedata = $arr_json_data;
            $this->page('wap/cart/cart_empty.html', true);
            return ;
        }

        // 购物车数据项的render
        $this->pagedata['item_section'] = $this->mCart->get_item_render();

        // 购物车数据项的render
        $this->pagedata['item_goods_section'] = $this->mCart->get_item_goods_render();

        // 优惠信息项render
        $this->pagedata['solution_section'] = $this->mCart->get_solution_render();

        //未享受的订单规则
        $this->pagedata['unuse_rule'] = $this->mCart->get_unuse_solution_cart($aCart);

        $imageDefault = app::get('image')->getConf('image.set');
        $this->pagedata['defaultImage'] = $imageDefault['S']['default_image'];
    }


    /*
     * item 禁用的数据类型如下：
      $_SESSION['cart_objects_disabled_item']
      array(
      'goods' => array(
        'goods_12_23' => array(
            'gift' => array(
                0 => true,
                3 => true,
                ),
            ),
        ),
      );
    */
    private function _item_to_disabled( &$aCart,$flag ) {

        foreach( kernel::servicelist('b2c_cart_object_apps') as $object ) {
            if( !is_object($object) ) continue;
            $o[$object->get_type()] = $object;
        }

        $arr_cart_disabled_session = $_SESSION['cart_objects_disabled_item'];
        foreach( (array)$aCart['object'] as $_obj_type => $_arr_by_obj_type ) {
            $tmp = $arr_cart_disabled_session[$_obj_type];
            if( isset($arr_cart_disabled_session[$_obj_type]) ) {
                if( !$o[$_obj_type] ) continue;
                if( !method_exists( $o[$_obj_type],'apply_to_disabled' ) ) continue;
                $aCart['object'][$_obj_type] = $o[$_obj_type]->apply_to_disabled( $_arr_by_obj_type, $tmp, $flag );
                $_SESSION['cart_objects_disabled_item'][$_obj_type] = $tmp;
            } else {
                if( $flag )
                    unset($_SESSION['cart_objects_disabled_item'][$obj_type]);
            }
        }
    }



    private function _v_cart_object ($temp, $row,$flag=false) {
        if( !$temp['quantity']) {
            if( isset($row['params']['adjunct']) && is_array($row['params']['adjunct']) ) {
                foreach( $row['params']['adjunct'] as $adjunct ) {
                    if( !isset($adjunct['adjunct']) || !is_array($adjunct['adjunct']) ) continue;
                    foreach( $adjunct['adjunct'] as $p_id => $p_quantity ) {
                        if( !isset($temp['adjunct'][$adjunct['group_id']][$p_id]) ) { $flag = false; continue; }
                        #if($temp[$adjunct['group_id']][$p_id]['quantity']!=$p_quantity) {
                            $this->update_obj_ident['index'] = array('adjunct');
                            $this->update_obj_ident['id'] = $p_id;
                            $flag = false;
                            break 2;
                        #}
                    }
                }
            }
            return $flag;
        }
        return $flag;
    }


    /*
     * 凑单
     * */
    function fororder(){
        $this->_response->set_header('Cache-Control', 'no-store, no-cache');
        $fororder_setting = app::get('b2c')->getConf('cart_fororder_setting');
        //每个TAB的商品数量
        $limit = $fororder_setting['fororder']['nums'];
        //价格区间 TAB
        $fororder_filter = $fororder_setting['fororder']['filter'];
        foreach($fororder_filter as $tab_key=>$tab_value){
            if(empty($tab_value['price_min']) || !$tab_value['price_min']){
                $new_fororder_tab[$tab_key]['tab_name'] = $tab_value['price_max'].'元以下';
            }elseif(empty($tab_value['price_max']) || $tab_value['price_max'] == 999999){
                $new_fororder_tab[$tab_key]['tab_name'] = $tab_value['price_min'].'元以上';
            }else{
                $new_fororder_tab[$tab_key]['tab_name'] = $tab_value['price_min'].'-'.$tab_value['price_max'].'元';
            }
            $new_fororder_tab[$tab_key]['tab_filter'] = $tab_value['price_min'].'-'.$tab_value['price_max'];
        }
        $this->pagedata['fororder_tab'] = $new_fororder_tab;

        if(isset($_POST['tab_name'])){
            $tab_name=$_POST['tab_name'];
            $view = 'wap/cart/cart_fororder_item.html';
        }else{
            $new_tab_name = current($new_fororder_tab);
            $tab_name=$new_tab_name['tab_filter'];
            $view = 'wap/cart/cart_fororder.html';
        }

        //获取商品
        if(!cachemgr::get('fororder_goods_data'.$tab_name,$list)){
            cachemgr::co_start();
            $filter = $this->fororder_filter($tab_name);
            $goods_model = app::get('b2c')->model('goods');
            $aGoods_list = $goods_model->getList("store,spec_desc,goods_id,name,image_default_id,price,nostore_sell",$filter,0,$limit,'price asc,last_modify desc');
            foreach($aGoods_list as $goods_key=>$goods){
                $goodsids[]= $goods['goods_id'];
                $list[$goods['goods_id']] = $goods;
            }
            $products = app::get('b2c')->model('products')->getList('goods_id,product_id,store,freez',array('goods_id'=>$goodsids,'marketable'=>'true','is_default'=>'true'),0,-1,'price asc');
            foreach( (array)$products as $pk=>$row ){
                $goods = $list[$row['goods_id']];
                if(($goods['store'] === null || $row['store'] - $row['freez']) > 0 || $goods['nostore_sell'] ){
                    $list[$row['goods_id']]['product_id'] = $row['product_id'];
                }else{
                    unset($list[$row['goods_id']]);
                }
            }
            cachemgr::set('fororder_goods_data'.$tab_name, $list, cachemgr::co_end());
        }

        $i = 1;
        foreach($list as $goods_item){
            if($i <= 4){
                $aGoods_list_before[] = $goods_item;
                $i ++;
            }else{
                $aGoods_list_last[] = $goods_item;
                $i++;
                if($i == 9) $i=1;
            }
        }

        $aGoods_list['before'] = $aGoods_list_before;
        $aGoods_list['last'] = $aGoods_list_last;

        $imageDefault = app::get('image')->getConf('image.set');
        $this->pagedata['defaultImage'] = $imageDefault['S']['default_image'];
        $this->pagedata['goods_list'] = $aGoods_list;
        echo $this->fetch($view);
    }

    //检查当前TAB是否有商品
    function _check_fororder($tab_name,&$msg){
        $filter = $this->fororder_filter($tab_name);
        $goods = app::get('b2c')->model('goods')->getList('goods_id',$filter);
        if(!$goods){
            $msg = 0;
            return false;
        }
        $msg = count($goods);
        return true;
    }

    //凑单TAB条件，现在默认为使用tab名称0-30作为条件
    function fororder_filter($fororder_tab_name){
        if(is_array($fororder_tab_name)){
            $price[0] = $fororder_tab_name['price_min'];
            $price[1] = $fororder_tab_name['price_max'];
        }else{
            $price = explode('-',$fororder_tab_name);
        }
        $filter['price'] = $price;
        $filter['marketable'] = 'true';
        return $filter;
    }

    function set_header(){
        header("Cache-Control:no-store, no-cache, must-revalidate"); // HTTP/1.1
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");// 强制查询etag
        header('Progma: no-cache');
        header('Content-Type:text/html; charset=utf-8');
    }
}

